Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat(dashboard-v2): ANTLR-composed apply-to-panels with an impact review dialog (#12181)

Ashwin Bhatkal6c957d1e8bdd
diff --git a/frontend/src/components/QueryBuilderV2/utils.ts b/frontend/src/components/QueryBuilderV2/utils.ts
index feaaf549b2..4d2a01cde9 100644
--- a/frontend/src/components/QueryBuilderV2/utils.ts
+++ b/frontend/src/components/QueryBuilderV2/utils.ts
@@ -770,6 +770,34 @@ export const removeVariableFromExpression = (
return removeKeysFromExpression(expression, keysToRemove, `$${variableName}`);
};
+// Appends `clause` as a top-level AND term, parenthesising the base only when it
+// has a top-level OR (AND binds tighter, so `a OR b AND c` would misbind).
+export const appendAndClause = (
+ expression: string | undefined,
+ clause: string,
+): string => {
+ const base = expression?.trim();
+ if (!base) {
+ return clause;
+ }
+
+ const chars = CharStreams.fromString(base);
+ const lexer = new FilterQueryLexer(chars);
+ lexer.removeErrorListeners();
+ const tokenStream = new CommonTokenStream(lexer);
+ const parser = new FilterQueryParser(tokenStream);
+ parser.removeErrorListeners();
+ const tree = parser.query();
+
+ if (parser.syntaxErrorsCount > 0) {
+ return `(${base}) AND ${clause}`;
+ }
+
+ const hasTopLevelOr =
+ tree.expression().orExpression().andExpression_list().length > 1;
+ return hasTopLevelOr ? `(${base}) AND ${clause}` : `${base} AND ${clause}`;
+};
+
/**
* Convert old having format to new having format
* @param having - Array of old having objects with columnName, op, and value
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableImpactDialog/VariableImpactDialog.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableImpactDialog/VariableImpactDialog.tsx
index 4e7a1e16a2..a577ed4bc2 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableImpactDialog/VariableImpactDialog.tsx
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableImpactDialog/VariableImpactDialog.tsx
@@ -54,11 +54,18 @@ function VariableImpactDialog({
useVariableImpactState(usages, open);
const isRename = mode === 'rename';
+ const isDelete = mode === 'delete';
const count = usages.length;
const plural = count === 1 ? '' : 's';
- const intro = isRename
- ? `$${variableName} is used in ${count} place${plural}. Review the updated queries before renaming to $${newName}.`
- : `$${variableName} is used in ${count} place${plural}. Edit or remove each usage before deleting.`;
+ let intro: string;
+ if (isRename) {
+ intro = `$${variableName} is used in ${count} place${plural}. Review the updated queries before renaming to $${newName}.`;
+ } else if (isDelete) {
+ intro = `$${variableName} is used in ${count} place${plural}. Edit or remove each usage before deleting.`;
+ } else {
+ intro = `Applying $${variableName} can update upto ${count} panel quer${count === 1 ? 'y' : 'ies'}. Review the changes before applying.`;
+ }
+ const confirmLabel = isRename ? 'Rename' : isDelete ? 'Delete' : 'Apply';
const footer = (
<div className={styles.footer}>
@@ -73,13 +80,13 @@ function VariableImpactDialog({
</Button>
<Button
variant="solid"
- color={isRename ? 'primary' : 'destructive'}
+ color={isDelete ? 'destructive' : 'primary'}
loading={isLoading}
onClick={(): void => onConfirm(resolvedUsages)}
testId="variable-impact-confirm"
>
<Check size={12} />
- {isRename ? 'Rename' : 'Delete'}
+ {confirmLabel}
</Button>
</div>
);
@@ -92,7 +99,14 @@ function VariableImpactDialog({
onClose();
}
}}
- title={isRename ? `Rename $${variableName}` : `Delete $${variableName}`}
+ title={
+ // eslint-disable-next-line no-nested-ternary
+ isRename
+ ? `Rename $${variableName}`
+ : isDelete
+ ? `Delete $${variableName}`
+ : `Apply $${variableName} to panels`
+ }
width="wide"
showCloseButton={false}
// Lift above the settings drawer (z ~1000); overlay off (it would only half-dim).
@@ -104,7 +118,9 @@ function VariableImpactDialog({
<Typography.Text className={styles.intro}>{intro}</Typography.Text>
<div className={styles.rows}>
{rows.map((row) => {
+ // Only warn on delete: an apply result is meant to reference the variable.
const stillReferences =
+ isDelete &&
row.included &&
textContainsVariableReference(row.resultingText, variableName);
return (
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/applyVariableToPanelsPatch.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/applyVariableToPanelsPatch.test.ts
index 870282bff5..8d4e9e185d 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/applyVariableToPanelsPatch.test.ts
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/applyVariableToPanelsPatch.test.ts
@@ -1,13 +1,6 @@
-import type {
- DashboardtypesDashboardSpecDTOPanels,
- DashboardtypesJSONPatchOperationDTO,
-} from 'api/generated/services/sigNoz.schemas';
+import type { DashboardtypesDashboardSpecDTOPanels } from 'api/generated/services/sigNoz.schemas';
-import {
- buildApplyVariableToPanelsPatch,
- buildSyncVariableToPanelsPatch,
- getPanelIdsReferencingVariable,
-} from '../utils/applyVariableToPanelsPatch';
+import { getPanelIdsReferencingVariable } from '../utils/applyVariableToPanelsPatch';
/** Minimal builder-query panel wrapped in a CompositeQuery, with a given filter. */
function compositePanel(filterExpression: string): unknown {
@@ -68,153 +61,12 @@ function listPanel(filterExpression: string): unknown {
};
}
-/** A PromQL panel — no builder filter, must be skipped. */
-function promqlPanel(): unknown {
- return {
- kind: 'panel',
- spec: {
- display: { title: '' },
- plugin: { kind: 'signoz/TimeSeries', spec: {} },
- queries: [
- {
- kind: 'promql',
- spec: {
- plugin: { kind: 'signoz/PromQLQuery', spec: { query: 'up' } },
- },
- },
- ],
- },
- };
-}
-
-/** Reads the first builder query's filter expression out of a patch op's value. */
-function expressionOf(
- op: DashboardtypesJSONPatchOperationDTO,
-): string | undefined {
- const queries = op.value as Array<{
- spec: { plugin: { kind: string; spec: any } };
- }>;
- const { plugin } = queries[0].spec;
- const builderSpec =
- plugin.kind === 'signoz/CompositeQuery'
- ? plugin.spec.queries[0].spec
- : plugin.spec;
- return builderSpec.filter?.expression;
-}
-
function panels(
map: Record<string, unknown>,
): DashboardtypesDashboardSpecDTOPanels {
return map as DashboardtypesDashboardSpecDTOPanels;
}
-describe('buildApplyVariableToPanelsPatch', () => {
- it('appends the clause to an existing filter (AND-joined)', () => {
- const ops = buildApplyVariableToPanelsPatch(
- panels({ p1: compositePanel('env = "prod"') }),
- 'service.name',
- 'svc',
- );
- expect(ops).toHaveLength(1);
- expect(ops[0]).toMatchObject({
- op: 'replace',
- path: '/spec/panels/p1/spec/queries',
- });
- expect(expressionOf(ops[0])).toBe('env = "prod" AND service.name IN $svc');
- });
-
- it('sets the clause when the filter is empty', () => {
- const ops = buildApplyVariableToPanelsPatch(
- panels({ p1: compositePanel('') }),
- 'service.name',
- 'svc',
- );
- expect(expressionOf(ops[0])).toBe('service.name IN $svc');
- });
-
- it('applies to a bare BuilderQuery (LIST) panel', () => {
- const ops = buildApplyVariableToPanelsPatch(
- panels({ p1: listPanel('') }),
- 'k8s.pod.name',
- 'pod',
- );
- expect(expressionOf(ops[0])).toBe('k8s.pod.name IN $pod');
- });
-
- it('is idempotent — re-applying does not duplicate the clause', () => {
- const ops = buildApplyVariableToPanelsPatch(
- panels({ p1: compositePanel('service.name IN $svc') }),
- 'service.name',
- 'svc',
- );
- expect(ops).toHaveLength(0);
- });
-
- it('only targets the requested panels', () => {
- const ops = buildApplyVariableToPanelsPatch(
- panels({ p1: compositePanel(''), p2: compositePanel('') }),
- 'service.name',
- 'svc',
- ['p2'],
- );
- expect(ops).toHaveLength(1);
- expect(ops[0].path).toBe('/spec/panels/p2/spec/queries');
- });
-
- it('skips PromQL panels (no builder filter)', () => {
- const ops = buildApplyVariableToPanelsPatch(
- panels({ p1: promqlPanel() }),
- 'service.name',
- 'svc',
- );
- expect(ops).toHaveLength(0);
- });
-
- it('returns nothing when attribute or name is missing', () => {
- expect(
- buildApplyVariableToPanelsPatch(
- panels({ p1: compositePanel('') }),
- '',
- 'svc',
- ),
- ).toHaveLength(0);
- });
-});
-
-describe('buildSyncVariableToPanelsPatch', () => {
- it('adds to selected panels and removes from the rest', () => {
- const ops = buildSyncVariableToPanelsPatch(
- panels({
- p1: compositePanel('service.name IN $svc'), // has it, not selected → remove
- p2: compositePanel(''), // selected → add
- p3: compositePanel('service.name IN $svc'), // has it, selected → unchanged
- }),
- 'service.name',
- 'svc',
- ['p2', 'p3'],
- );
- const byPath = Object.fromEntries(ops.map((op) => [op.path, op]));
- expect(Object.keys(byPath).sort()).toStrictEqual([
- '/spec/panels/p1/spec/queries',
- '/spec/panels/p2/spec/queries',
- ]);
- expect(expressionOf(byPath['/spec/panels/p1/spec/queries'])).toBe('');
- expect(expressionOf(byPath['/spec/panels/p2/spec/queries'])).toBe(
- 'service.name IN $svc',
- );
- });
-
- it('removing keeps other clauses intact', () => {
- const ops = buildSyncVariableToPanelsPatch(
- panels({ p1: compositePanel('env = "prod" AND service.name IN $svc') }),
- 'service.name',
- 'svc',
- [],
- );
- expect(expressionOf(ops[0])).toBe('env = "prod"');
- });
-});
-
describe('getPanelIdsReferencingVariable', () => {
it('returns only panels whose filter references the variable', () => {
const ids = getPanelIdsReferencingVariable(
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/useVariableListActions.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/useVariableListActions.test.ts
new file mode 100644
index 0000000000..27d8ac445c
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/useVariableListActions.test.ts
@@ -0,0 +1,113 @@
+import { act, renderHook } from '@testing-library/react';
+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
+
+import { useVariableListActions } from '../hooks/useVariableListActions';
+import {
+ emptyVariableFormModel,
+ type VariableFormModel,
+} from '../variableFormModel';
+
+jest.mock('../../../store/useDashboardStore', () => ({
+ useDashboardStore: (
+ selector: (s: { dashboardId: string }) => unknown,
+ ): unknown => selector({ dashboardId: 'd1' }),
+}));
+jest.mock('api/common/logEvent', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+jest.mock('@signozhq/ui/sonner', () => ({
+ toast: { success: jest.fn(), error: jest.fn(), info: jest.fn() },
+}));
+
+function builderPanel(name: string, expression: string): unknown {
+ return {
+ spec: {
+ display: { name },
+ queries: [
+ {
+ spec: {
+ plugin: { kind: 'signoz/BuilderQuery', spec: { filter: { expression } } },
+ },
+ },
+ ],
+ },
+ };
+}
+
+function dashboard(
+ panels: Record<string, unknown>,
+): DashboardtypesGettableDashboardV2DTO {
+ return {
+ spec: { panels, variables: [] },
+ } as unknown as DashboardtypesGettableDashboardV2DTO;
+}
+
+function dynamicVar(name: string, attribute: string): VariableFormModel {
+ return {
+ ...emptyVariableFormModel(),
+ name,
+ type: 'DYNAMIC',
+ dynamicAttribute: attribute,
+ };
+}
+
+function renderActions(
+ dash: DashboardtypesGettableDashboardV2DTO,
+ variables: VariableFormModel[],
+) {
+ return renderHook(() =>
+ useVariableListActions({
+ dashboard: dash,
+ variables,
+ setVariables: jest.fn(),
+ isEditing: null,
+ setIsEditing: jest.fn(),
+ save: jest.fn().mockResolvedValue(true),
+ patchAsync: jest.fn().mockResolvedValue(undefined),
+ }),
+ );
+}
+
+describe('useVariableListActions — apply to all', () => {
+ it('marks a variable applied-to-all only when every panel already references it', () => {
+ const notApplied = renderActions(dashboard({ p1: builderPanel('P1', '') }), [
+ dynamicVar('pod', 'k8s.pod.name'),
+ ]);
+ expect(notApplied.result.current.appliedToAllNames.has('pod')).toBe(false);
+
+ const applied = renderActions(
+ dashboard({ p1: builderPanel('P1', 'k8s.pod.name IN $pod') }),
+ [dynamicVar('pod', 'k8s.pod.name')],
+ );
+ expect(applied.result.current.appliedToAllNames.has('pod')).toBe(true);
+ });
+
+ it('requestApplyToAll opens an apply-mode impact for all panels', () => {
+ const { result } = renderActions(
+ dashboard({ p1: builderPanel('P1', ''), p2: builderPanel('P2', '') }),
+ [dynamicVar('pod', 'k8s.pod.name')],
+ );
+
+ act(() => result.current.requestApplyToAll(0));
+
+ const { impact } = result.current;
+ expect(impact?.mode).toBe('apply');
+ expect(impact?.origin).toBe('applyToAll');
+ expect(impact?.variableName).toBe('pod');
+ expect(impact?.usages.map((u) => u.sourceId).sort()).toStrictEqual([
+ 'p1',
+ 'p2',
+ ]);
+ });
+
+ it('requestApplyToAll is a no-op when nothing is left to apply', () => {
+ const { result } = renderActions(
+ dashboard({ p1: builderPanel('P1', 'k8s.pod.name IN $pod') }),
+ [dynamicVar('pod', 'k8s.pod.name')],
+ );
+
+ act(() => result.current.requestApplyToAll(0));
+ expect(result.current.impact).toBeNull();
+ });
+});
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/variableUsages.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/variableUsages.test.ts
index 2580b7da6a..721a532586 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/variableUsages.test.ts
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/__tests__/variableUsages.test.ts
@@ -4,7 +4,11 @@ import {
emptyVariableFormModel,
type VariableFormModel,
} from '../variableFormModel';
-import { findVariableUsages } from '../utils/variableUsages';
+import {
+ findApplyUsages,
+ findVariableUsages,
+ isVariableAppliedToAllPanels,
+} from '../utils/variableUsages';
// Identity adapter so `spec.variables` can be plain form models in the test.
jest.mock('../variableAdapters', () => ({
@@ -96,3 +100,98 @@ describe('findVariableUsages', () => {
expect(findVariableUsages(dash, 'nope', 'delete')).toStrictEqual([]);
});
});
+
+describe('findApplyUsages', () => {
+ const dash = dashboard(
+ {
+ empty: builderPanel('Empty', ''),
+ ored: builderPanel('Ored', "a = 'x' OR b = 'y'"),
+ has: builderPanel('Has it', 'k8s.pod.name IN $pod'),
+ prom: promqlPanel('Prom', 'up'),
+ promRef: promqlPanel('Prom Ref', 'up{pod="$pod"}'),
+ },
+ [],
+ );
+
+ it('appends the clause to selected builder panels, parenthesising an OR', () => {
+ const usages = findApplyUsages(dash, 'k8s.pod.name', 'pod', 'pod', [
+ 'empty',
+ 'ored',
+ ]);
+ const byId = Object.fromEntries(usages.map((u) => [u.id, u.resultingText]));
+ expect(byId['panel:empty:0']).toBe('k8s.pod.name IN $pod');
+ expect(byId['panel:ored:0']).toBe(
+ "(a = 'x' OR b = 'y') AND k8s.pod.name IN $pod",
+ );
+ });
+
+ it('skips a selected panel that already carries the clause (idempotent)', () => {
+ const usages = findApplyUsages(dash, 'k8s.pod.name', 'pod', 'pod', ['has']);
+ expect(usages).toStrictEqual([]);
+ });
+
+ it('removes the clause from an unselected builder panel that has it', () => {
+ const usages = findApplyUsages(dash, 'k8s.pod.name', 'pod', 'pod', ['empty']);
+ const has = usages.find((u) => u.id === 'panel:has:0');
+ expect(has?.resultingText).toBe('');
+ });
+
+ it('lists a selected PromQL panel as an editable, unchanged row', () => {
+ const usages = findApplyUsages(dash, 'k8s.pod.name', 'pod', 'pod', ['prom']);
+ const prom = usages.find((u) => u.id === 'panel:prom:0');
+ expect(prom?.kind).toBe('promql');
+ // Never auto-injected — the row defaults to the current text for manual edits.
+ expect(prom?.currentText).toBe('up');
+ expect(prom?.resultingText).toBe('up');
+ });
+
+ it('skips a selected non-builder panel that already references the variable', () => {
+ const usages = findApplyUsages(dash, 'k8s.pod.name', 'pod', 'pod', [
+ 'promRef',
+ ]);
+ expect(usages.some((u) => u.sourceId === 'promRef')).toBe(false);
+ });
+
+ it('never touches unselected non-builder panels', () => {
+ const usages = findApplyUsages(dash, 'k8s.pod.name', 'pod', 'pod', ['empty']);
+ expect(usages.some((u) => u.sourceId === 'prom')).toBe(false);
+ expect(usages.some((u) => u.sourceId === 'promRef')).toBe(false);
+ });
+
+ it('returns nothing when every selected query already references the variable', () => {
+ // The "applied to all" signal: builder carries the clause, PromQL references it.
+ const usages = findApplyUsages(dash, 'k8s.pod.name', 'pod', 'pod', [
+ 'has',
+ 'promRef',
+ ]);
+ expect(usages).toStrictEqual([]);
+ });
+});
+
+describe('isVariableAppliedToAllPanels', () => {
+ it('is true only when every panel query references the variable', () => {
+ const covered = dashboard(
+ {
+ b: builderPanel('B', 'k8s.pod.name IN $pod'),
+ p: promqlPanel('P', 'up{pod="$pod"}'),
+ },
+ [],
+ );
+ expect(isVariableAppliedToAllPanels(covered, 'k8s.pod.name', 'pod')).toBe(
+ true,
+ );
+ });
+
+ it('is false when any panel query is missing the reference', () => {
+ const missing = dashboard(
+ {
+ b: builderPanel('B', 'k8s.pod.name IN $pod'),
+ p: promqlPanel('P', 'up'),
+ },
+ [],
+ );
+ expect(isVariableAppliedToAllPanels(missing, 'k8s.pod.name', 'pod')).toBe(
+ false,
+ );
+ });
+});
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/ApplyToAllDialog/ApplyToAllDialog.module.scss b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/ApplyToAllDialog/ApplyToAllDialog.module.scss
deleted file mode 100644
index 5658edb971..0000000000
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/ApplyToAllDialog/ApplyToAllDialog.module.scss
+++ /dev/null
@@ -1,16 +0,0 @@
-.body {
- font-size: 13px;
- line-height: 20px;
- color: var(--l2-foreground);
-}
-
-.variableName {
- font-family: 'Space Mono', monospace;
- color: var(--bg-robin-400);
-}
-
-.footer {
- display: flex;
- justify-content: flex-end;
- gap: 8px;
-}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/ApplyToAllDialog/ApplyToAllDialog.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/ApplyToAllDialog/ApplyToAllDialog.tsx
deleted file mode 100644
index f6a9f199f7..0000000000
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/ApplyToAllDialog/ApplyToAllDialog.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { Check, X } from '@signozhq/icons';
-import { Button } from '@signozhq/ui/button';
-import { DialogWrapper } from '@signozhq/ui/dialog';
-
-import styles from './ApplyToAllDialog.module.scss';
-
-interface ApplyToAllDialogProps {
- open: boolean;
- variableName: string;
- isLoading: boolean;
- onConfirm: () => void;
- onClose: () => void;
-}
-
-/** Confirms applying a dynamic variable as a filter to every panel. */
-function ApplyToAllDialog({
- open,
- variableName,
- isLoading,
- onConfirm,
- onClose,
-}: ApplyToAllDialogProps): JSX.Element {
- const footer = (
- <div className={styles.footer}>
- <Button variant="solid" color="secondary" onClick={onClose}>
- <X size={12} />
- Cancel
- </Button>
- <Button
- variant="solid"
- color="primary"
- loading={isLoading}
- onClick={onConfirm}
- testId="confirm-apply-to-all"
- >
- <Check size={12} />
- Apply to all
- </Button>
- </div>
- );
-
- return (
- <DialogWrapper
- open={open}
- onOpenChange={(isOpen): void => {
- if (!isOpen) {
- onClose();
- }
- }}
- title="Apply variable to all panels"
- width="narrow"
- showCloseButton={false}
- // Lift above the settings drawer (z ~1000); overlay off (it would only half-dim).
- style={{ zIndex: 1100 }}
- showOverlay={false}
- footer={footer}
- >
- <div className={styles.body}>
- Add <span className={styles.variableName}>${variableName}</span> as a filter
- to every panel on this dashboard. Panels that already reference it are left
- unchanged.
- </div>
- </DialogWrapper>
- );
-}
-
-export default ApplyToAllDialog;
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariableRow/VariableRow.module.scss b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariableRow/VariableRow.module.scss
index df658ac09e..4de3915697 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariableRow/VariableRow.module.scss
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariableRow/VariableRow.module.scss
@@ -64,7 +64,7 @@ $grid-columns: minmax(0, 2fr) minmax(0, 3fr);
.rowActions {
position: absolute;
- top: 8px;
+ top: 6px;
right: 0;
display: flex;
align-items: center;
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariableRow/VariableRow.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariableRow/VariableRow.tsx
index e443da49c1..1952592e56 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariableRow/VariableRow.tsx
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariableRow/VariableRow.tsx
@@ -22,6 +22,8 @@ interface VariableRowProps {
onCancelDelete: () => void;
/** Apply this variable's filter to all panels. Dynamic variables only. */
onApplyToAll: (index: number) => void;
+ /** True when this dynamic variable is already applied to every panel. */
+ isAppliedToAll: boolean;
}
/** A single draggable variable row in the two-column (name / description) table. */
@@ -35,6 +37,7 @@ function VariableRow({
onConfirmDelete,
onCancelDelete,
onApplyToAll,
+ isAppliedToAll,
}: VariableRowProps): JSX.Element {
const {
attributes,
@@ -121,12 +124,17 @@ function VariableRow({
{variable.type === 'DYNAMIC' ? (
<TooltipSimple
side="top"
- title="Add this variable as a filter to every panel"
+ title={
+ isAppliedToAll
+ ? 'Already applied to all panels'
+ : 'Add this variable as a filter to every panel'
+ }
>
<Button
variant="ghost"
color="secondary"
size="sm"
+ disabled={isAppliedToAll}
className={styles.applyAllButton}
onClick={(): void => onApplyToAll(index)}
testId={`variable-apply-all-${variable.name}`}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariablesList/VariablesList.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariablesList/VariablesList.tsx
index e40ff89f4d..a26fbc7aa0 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariablesList/VariablesList.tsx
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/components/VariablesList/VariablesList.tsx
@@ -26,6 +26,8 @@ interface VariablesListProps {
onCancelDelete: () => void;
onMove: (from: number, to: number) => void;
onApplyToAll: (index: number) => void;
+ /** Names of dynamic variables already applied to every panel. */
+ appliedToAllNames: Set<string>;
}
function VariablesList({
@@ -38,6 +40,7 @@ function VariablesList({
onCancelDelete,
onMove,
onApplyToAll,
+ appliedToAllNames,
}: VariablesListProps): JSX.Element {
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 1 } }),
@@ -82,6 +85,7 @@ function VariablesList({
onConfirmDelete={onConfirmDelete}
onCancelDelete={onCancelDelete}
onApplyToAll={onApplyToAll}
+ isAppliedToAll={appliedToAllNames.has(variable.name)}
/>
))}
</div>
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/hooks/useVariableListActions.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/hooks/useVariableListActions.ts
index cef3b65484..08460558b5 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/hooks/useVariableListActions.ts
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/hooks/useVariableListActions.ts
@@ -2,6 +2,7 @@ import {
type Dispatch,
type SetStateAction,
useCallback,
+ useMemo,
useState,
} from 'react';
import logEvent from 'api/common/logEvent';
@@ -13,7 +14,6 @@ import type {
import { DashboardDetailEvents } from 'pages/DashboardPageV2/constants/events';
import { useDashboardStore } from '../../../store/useDashboardStore';
-import { buildSyncVariableToPanelsPatch } from '../utils/applyVariableToPanelsPatch';
import {
VARIABLE_TYPE_EVENT_LABEL,
type VariableFormModel,
@@ -23,7 +23,9 @@ import {
buildVariableImpactPatch,
} from '../utils/variableImpactPatch';
import {
+ findApplyUsages,
findVariableUsages,
+ isVariableAppliedToAllPanels,
type VariableImpactMode,
type VariableUsage,
} from '../utils/variableUsages';
@@ -40,6 +42,8 @@ export interface VariableImpact {
newName?: string;
usages: VariableUsage[];
nextVariables: VariableFormModel[];
+ /** Where an `apply` impact came from — drives the confirm analytics event. */
+ origin?: 'form' | 'applyToAll';
}
interface UseVariableListActionsParams {
@@ -64,6 +68,9 @@ interface UseVariableListActions {
handleMove: (from: number, to: number) => void;
requestDelete: (index: number) => void;
handleConfirmDelete: (index: number) => void;
+ requestApplyToAll: (index: number) => void;
+ /** Names of dynamic variables already applied to every panel (button disabled). */
+ appliedToAllNames: Set<string>;
handleImpactConfirm: (resolvedUsages: VariableUsage[]) => Promise<void>;
}
@@ -107,68 +114,52 @@ export function useVariableListActions({
next[editingIndex] = formModel;
}
- // A rename that other queries/variables reference must be reviewed first, so
- // the references are rewritten alongside the rename (never left dangling).
- if (oldName && oldName !== formModel.name) {
- const usages = findVariableUsages(
- dashboard,
- oldName,
- 'rename',
- formModel.name,
- );
- if (usages.length > 0) {
- setIsEditing(null);
- setImpact({
- mode: 'rename',
- variableName: oldName,
- newName: formModel.name,
- usages,
- nextVariables: next,
- });
- return;
- }
+ const isRename = !!oldName && oldName !== formModel.name;
+ // Both rename and apply-to-panels edits are reviewed in the impact dialog
+ // before persisting — never applied silently.
+ const renameUsages = isRename
+ ? findVariableUsages(dashboard, oldName as string, 'rename', formModel.name)
+ : [];
+ const applyUsages =
+ formModel.type === 'DYNAMIC' && formModel.dynamicAttribute
+ ? findApplyUsages(
+ dashboard,
+ formModel.dynamicAttribute,
+ formModel.name,
+ oldName ?? formModel.name,
+ selectedPanelIds,
+ )
+ : [];
+
+ // Apply usages win per (panel, envelope) over a plain rename rewrite.
+ const byId = new Map<string, VariableUsage>();
+ renameUsages.forEach((usage) => byId.set(usage.id, usage));
+ applyUsages.forEach((usage) => byId.set(usage.id, usage));
+ const usages = [...byId.values()];
+
+ if (usages.length > 0) {
+ setIsEditing(null);
+ setImpact({
+ mode: isRename ? 'rename' : 'apply',
+ variableName: oldName ?? formModel.name,
+ newName: formModel.name,
+ usages,
+ nextVariables: next,
+ });
+ return;
}
+ // No cross-query impact — persist directly; keep the form open on failure.
void (async (): Promise<void> => {
const saved = await save(next);
if (!saved) {
return;
}
-
setIsEditing(null);
setVariables(next);
-
- if (formModel.type !== 'DYNAMIC') {
- return;
- }
-
- const ops = buildSyncVariableToPanelsPatch(
- dashboard.spec.panels,
- formModel.dynamicAttribute,
- formModel.name,
- selectedPanelIds,
- );
-
- if (ops.length === 0) {
- return;
- }
-
- try {
- await patchAsync(ops);
- } catch {
- toast.error('Could not update panels');
- }
})();
},
- [
- dashboard,
- isEditing,
- patchAsync,
- save,
- setIsEditing,
- setVariables,
- variables,
- ],
+ [dashboard, isEditing, save, setIsEditing, setVariables, variables],
);
const handleMove = useCallback(
@@ -226,6 +217,57 @@ export function useVariableListActions({
[dashboard, variables],
);
+ // "Apply to all": review the additive changes across every panel before applying.
+ const requestApplyToAll = useCallback(
+ (index: number): void => {
+ const variable = variables[index];
+ if (!variable || variable.type !== 'DYNAMIC' || !variable.dynamicAttribute) {
+ return;
+ }
+ const allPanelIds = Object.keys(dashboard.spec.panels ?? {});
+ const usages = findApplyUsages(
+ dashboard,
+ variable.dynamicAttribute,
+ variable.name,
+ variable.name,
+ allPanelIds,
+ );
+ if (usages.length === 0) {
+ return;
+ }
+ setImpact({
+ mode: 'apply',
+ variableName: variable.name,
+ newName: variable.name,
+ usages,
+ nextVariables: variables,
+ origin: 'applyToAll',
+ });
+ },
+ [dashboard, variables],
+ );
+
+ // A dynamic variable is "applied to all" when every panel query already
+ // references it — i.e. the apply review would be empty. Disables the button.
+ const appliedToAllNames = useMemo(() => {
+ const names = new Set<string>();
+ variables.forEach((variable) => {
+ if (variable.type !== 'DYNAMIC' || !variable.dynamicAttribute) {
+ return;
+ }
+ if (
+ isVariableAppliedToAllPanels(
+ dashboard,
+ variable.dynamicAttribute,
+ variable.name,
+ )
+ ) {
+ names.add(variable.name);
+ }
+ });
+ return names;
+ }, [dashboard, variables]);
+
// Applies a resolved rename/delete: the variables array (rename/delete + edited
// variable queries) and each touched panel's queries, in one atomic patch.
const handleImpactConfirm = useCallback(
@@ -245,11 +287,15 @@ export function useVariableListActions({
setVariables(nextVariables);
try {
await patchAsync(ops);
- toast.success(
- impact.mode === 'rename'
- ? `Renamed to $${impact.newName}`
- : `Deleted $${impact.variableName}`,
- );
+ let message: string;
+ if (impact.mode === 'rename') {
+ message = `Renamed to $${impact.newName}`;
+ } else if (impact.mode === 'apply') {
+ message = `Applied $${impact.variableName} to panels`;
+ } else {
+ message = `Deleted $${impact.variableName}`;
+ }
+ toast.success(message);
if (impact.mode === 'delete') {
const deleted = variables.find((v) => v.name === impact.variableName);
void logEvent(DashboardDetailEvents.VariableDeleted, {
@@ -259,13 +305,22 @@ export function useVariableListActions({
hadReferences: true,
dashboardId,
});
+ } else if (impact.mode === 'apply' && impact.origin === 'applyToAll') {
+ void logEvent(DashboardDetailEvents.ApplyToAllConfirmed, {
+ variableType: 'dynamic',
+ dashboardId,
+ });
}
} catch {
- toast.error(
- impact.mode === 'rename'
- ? 'Could not rename the variable'
- : 'Could not delete the variable',
- );
+ let message: string;
+ if (impact.mode === 'rename') {
+ message = 'Could not rename the variable';
+ } else if (impact.mode === 'apply') {
+ message = 'Could not apply the variable to panels';
+ } else {
+ message = 'Could not delete the variable';
+ }
+ toast.error(message);
}
setImpact(null);
},
@@ -281,6 +336,8 @@ export function useVariableListActions({
handleMove,
requestDelete,
handleConfirmDelete,
+ requestApplyToAll,
+ appliedToAllNames,
handleImpactConfirm,
};
}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/index.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/index.tsx
index 5faaedbb0d..bec82bc793 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/index.tsx
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/index.tsx
@@ -1,17 +1,11 @@
import { useEffect, useMemo, useState } from 'react';
-import { toast } from '@signozhq/ui/sonner';
-import logEvent from 'api/common/logEvent';
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import cx from 'classnames';
-import { DashboardDetailEvents } from 'pages/DashboardPageV2/constants/events';
import settingsStyles from '../DashboardSettings.module.scss';
import { useOptimisticPatch } from '../../hooks/useOptimisticPatch';
import { useDashboardStore } from '../../store/useDashboardStore';
-import {
- buildApplyVariableToPanelsPatch,
- getPanelIdsReferencingVariable,
-} from './utils/applyVariableToPanelsPatch';
+import { getPanelIdsReferencingVariable } from './utils/applyVariableToPanelsPatch';
import { useSaveVariables } from './hooks/useSaveVariables';
import { useVariableListActions } from './hooks/useVariableListActions';
import { dtoToFormModel } from './variableAdapters';
@@ -24,7 +18,6 @@ import VariableImpactDialog from './VariableImpactDialog/VariableImpactDialog';
import VariablesList from './components/VariablesList/VariablesList';
import styles from './Variables.module.scss';
import AddVariableButton from './components/AddVariableButton';
-import ApplyToAllDialog from './components/ApplyToAllDialog/ApplyToAllDialog';
import NoVariablesCard from './components/NoVariablesCard/NoVariablesCard';
import { EditingState } from './types';
@@ -34,7 +27,6 @@ interface VariablesSettingsProps {
function VariablesSettings({ dashboard }: VariablesSettingsProps): JSX.Element {
const isEditable = useDashboardStore((s) => s.isEditable);
- const dashboardId = useDashboardStore((s) => s.dashboardId);
// The drawer destroys on close, so reading this once on mount is enough to
// open the add-form when deep-linked (e.g. the bar's "Add variable" button).
const openAddOnMount = useDashboardStore(
@@ -59,7 +51,6 @@ function VariablesSettings({ dashboard }: VariablesSettingsProps): JSX.Element {
const [isEditing, setIsEditing] = useState<EditingState>(
openAddOnMount && isEditable ? { type: 'new' } : null,
);
- const [applyToAllIndex, setApplyToAllIndex] = useState<number | null>(null);
const {
confirmDeleteIndex,
@@ -70,6 +61,8 @@ function VariablesSettings({ dashboard }: VariablesSettingsProps): JSX.Element {
handleMove,
requestDelete,
handleConfirmDelete,
+ requestApplyToAll,
+ appliedToAllNames,
handleImpactConfirm,
} = useVariableListActions({
dashboard,
@@ -116,36 +109,6 @@ function VariablesSettings({ dashboard }: VariablesSettingsProps): JSX.Element {
);
}, [editingFormModel, dashboard.spec.panels]);
- const applyToAllVariable =
- applyToAllIndex === null ? null : variables[applyToAllIndex];
-
- const handleConfirmApplyToAll = async (): Promise<void> => {
- if (!applyToAllVariable) {
- return;
- }
- const ops = buildApplyVariableToPanelsPatch(
- dashboard.spec.panels,
- applyToAllVariable.dynamicAttribute,
- applyToAllVariable.name,
- );
- if (ops.length === 0) {
- toast.info('No panels needed this filter.');
- setApplyToAllIndex(null);
- return;
- }
- try {
- await patchAsync(ops);
- toast.success(`Applied $${applyToAllVariable.name} to all panels`);
- void logEvent(DashboardDetailEvents.ApplyToAllConfirmed, {
- variableType: 'dynamic',
- dashboardId,
- });
- } catch {
- toast.error('Could not apply the variable to panels');
- }
- setApplyToAllIndex(null);
- };
-
if (editingFormModel) {
return (
<VariableForm
@@ -176,20 +139,14 @@ function VariablesSettings({ dashboard }: VariablesSettingsProps): JSX.Element {
onConfirmDelete={handleConfirmDelete}
onCancelDelete={(): void => setConfirmDeleteIndex(null)}
onMove={handleMove}
- onApplyToAll={(index): void => setApplyToAllIndex(index)}
+ onApplyToAll={requestApplyToAll}
+ appliedToAllNames={appliedToAllNames}
/>
<div className={styles.footer}>
<AddVariableButton isEditable={isEditable} setIsEditing={setIsEditing} />
</div>
</>
)}
- <ApplyToAllDialog
- open={applyToAllVariable !== null}
- variableName={applyToAllVariable?.name ?? ''}
- isLoading={isPatching}
- onConfirm={(): void => void handleConfirmApplyToAll()}
- onClose={(): void => setApplyToAllIndex(null)}
- />
<VariableImpactDialog
open={impact !== null}
mode={impact?.mode ?? 'delete'}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/utils/applyVariableToPanelsPatch.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/utils/applyVariableToPanelsPatch.ts
index 4a524bee6b..fa20e8df05 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/utils/applyVariableToPanelsPatch.ts
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/utils/applyVariableToPanelsPatch.ts
@@ -1,21 +1,15 @@
import type {
DashboardtypesDashboardSpecDTOPanels,
- DashboardtypesJSONPatchOperationDTO,
DashboardtypesQueryDTO,
Querybuildertypesv5BuilderQuerySpecDTO,
Querybuildertypesv5CompositeQueryDTO,
Querybuildertypesv5QueryEnvelopeBuilderDTO,
} from 'api/generated/services/sigNoz.schemas';
-import { cloneDeep } from 'lodash-es';
-
-// Injects/removes a dynamic variable's filter (`attribute IN $name`) in panel
-// builder queries as JSON-Patch ops. Only builder queries carry a filter.
function clauseFor(attribute: string, variableName: string): string {
return `${attribute} IN $${variableName}`;
}
-/** Runs `fn` on every builder-query spec in a panel's single query (Composite or bare Builder). */
function forEachBuilderSpec(
queries: DashboardtypesQueryDTO[],
fn: (spec: Querybuildertypesv5BuilderQuerySpecDTO) => void,
@@ -39,48 +33,6 @@ function forEachBuilderSpec(
}
}
-/** Appends the clause to every builder query's filter. Returns whether anything changed. */
-function addClause(queries: DashboardtypesQueryDTO[], clause: string): boolean {
- let changed = false;
- forEachBuilderSpec(queries, (spec) => {
- const existing = spec.filter?.expression?.trim();
- // Idempotent: a repeated apply must not stack duplicate clauses.
- if (existing?.includes(clause)) {
- return;
- }
- spec.filter = {
- expression: existing ? `${existing} AND ${clause}` : clause,
- };
- changed = true;
- });
- return changed;
-}
-
-/** Removes the managed clause (an ` AND `-joined part) from every builder filter. */
-function removeClause(
- queries: DashboardtypesQueryDTO[],
- clause: string,
-): boolean {
- let changed = false;
- forEachBuilderSpec(queries, (spec) => {
- const existing = spec.filter?.expression;
- if (!existing) {
- return;
- }
- const parts = existing
- .split(' AND ')
- .map((part) => part.trim())
- .filter(Boolean);
- const kept = parts.filter((part) => part !== clause);
- if (kept.length !== parts.length) {
- spec.filter = { expression: kept.join(' AND ') };
- changed = true;
- }
- });
- return changed;
-}
-
-/** Whether any builder query in the panel already carries the clause. */
function panelHasClause(
queries: DashboardtypesQueryDTO[],
clause: string,
@@ -94,74 +46,6 @@ function panelHasClause(
return has;
}
-function replaceQueriesOp(
- panelId: string,
- queries: DashboardtypesQueryDTO[],
-): DashboardtypesJSONPatchOperationDTO {
- return {
- op: 'replace' as DashboardtypesJSONPatchOperationDTO['op'],
- path: `/spec/panels/${panelId}/spec/queries`,
- value: queries,
- };
-}
-
-/** Add-only: inject the variable's filter into the given panels (default: all). */
-export function buildApplyVariableToPanelsPatch(
- panels: DashboardtypesDashboardSpecDTOPanels,
- attribute: string,
- variableName: string,
- targetPanelIds?: string[],
-): DashboardtypesJSONPatchOperationDTO[] {
- if (!attribute || !variableName) {
- return [];
- }
- const clause = clauseFor(attribute, variableName);
- const ids = targetPanelIds ?? Object.keys(panels);
-
- const ops: DashboardtypesJSONPatchOperationDTO[] = [];
- ids.forEach((id) => {
- const panel = panels[id];
- if (!panel?.spec?.queries?.length) {
- return;
- }
- const queries = cloneDeep(panel.spec.queries);
- if (addClause(queries, clause)) {
- ops.push(replaceQueriesOp(id, queries));
- }
- });
- return ops;
-}
-
-/** Full sync: selected panels get the clause; every other panel has it removed. */
-export function buildSyncVariableToPanelsPatch(
- panels: DashboardtypesDashboardSpecDTOPanels,
- attribute: string,
- variableName: string,
- selectedPanelIds: string[],
-): DashboardtypesJSONPatchOperationDTO[] {
- if (!attribute || !variableName) {
- return [];
- }
- const clause = clauseFor(attribute, variableName);
- const selected = new Set(selectedPanelIds);
-
- const ops: DashboardtypesJSONPatchOperationDTO[] = [];
- Object.keys(panels).forEach((id) => {
- const panel = panels[id];
- if (!panel?.spec?.queries?.length) {
- return;
- }
- const queries = cloneDeep(panel.spec.queries);
- const changed = selected.has(id)
- ? addClause(queries, clause)
- : removeClause(queries, clause);
- if (changed) {
- ops.push(replaceQueriesOp(id, queries));
- }
- });
- return ops;
-}
-
/** Panel ids whose queries currently reference the variable — pre-populates the picker. */
export function getPanelIdsReferencingVariable(
panels: DashboardtypesDashboardSpecDTOPanels,
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/utils/variableUsages.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/utils/variableUsages.ts
index 923d8d53d0..60c3adce62 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/utils/variableUsages.ts
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/utils/variableUsages.ts
@@ -2,7 +2,10 @@ import type {
DashboardtypesGettableDashboardV2DTO,
Querybuildertypesv5QueryEnvelopeDTO,
} from 'api/generated/services/sigNoz.schemas';
-import { removeVariableFromExpression } from 'components/QueryBuilderV2/utils';
+import {
+ appendAndClause,
+ removeVariableFromExpression,
+} from 'components/QueryBuilderV2/utils';
import {
rewriteVariableReferences,
textContainsVariableReference,
@@ -18,8 +21,7 @@ export type VariableUsageKind =
| 'clickhouse'
| 'variable';
-/** Whether the impact is a rename (rewrite refs) or a delete (remove refs). */
-export type VariableImpactMode = 'rename' | 'delete';
+export type VariableImpactMode = 'rename' | 'delete' | 'apply';
/**
* One place a variable is referenced — a panel query's builder filter expression,
@@ -161,3 +163,118 @@ export function findVariableUsages(
return usages;
}
+
+// `matchName` is the name in the current query text (the old name during a
+// simultaneous rename); `injectName` is written into newly added clauses. Equal
+// outside of a rename.
+export function findApplyUsages(
+ dashboard: DashboardtypesGettableDashboardV2DTO,
+ attribute: string,
+ injectName: string,
+ matchName: string,
+ selectedPanelIds: string[],
+): VariableUsage[] {
+ if (!attribute || !injectName) {
+ return [];
+ }
+ const clause = `${attribute} IN $${injectName}`;
+ const existingClause = `${attribute} IN $${matchName}`;
+ const selected = new Set(selectedPanelIds);
+ const usages: VariableUsage[] = [];
+
+ Object.entries(dashboard.spec.panels ?? {}).forEach(([panelId, panel]) => {
+ const queries = panel?.spec?.queries;
+ if (!queries?.length) {
+ return;
+ }
+ toQueryEnvelopes(queries).forEach((envelope, index) => {
+ const pushUsage = (
+ kind: VariableUsageKind,
+ currentText: string,
+ resultingText: string,
+ ): void => {
+ usages.push({
+ id: `panel:${panelId}:${index}`,
+ sourceType: 'panel',
+ sourceId: panelId,
+ sourceLabel: panel.spec?.display?.name || panelId,
+ kind,
+ envelopeIndex: index,
+ currentText,
+ resultingText,
+ });
+ };
+
+ if (envelope.type === 'builder_query') {
+ const spec = envelope.spec as
+ | { filter?: { expression?: string } }
+ | undefined;
+ const current = spec?.filter?.expression ?? '';
+ if (selected.has(panelId)) {
+ // Already carries the clause (under either name) — a rename usage, if
+ // any, fixes the name; don't append a duplicate.
+ if (current.includes(clause) || current.includes(existingClause)) {
+ return;
+ }
+ pushUsage('builder', current, appendAndClause(current, clause));
+ } else {
+ const next = removeVariableFromExpression(current, matchName);
+ if (next !== current) {
+ pushUsage('builder', current, next);
+ }
+ }
+ return;
+ }
+
+ // PromQL/ClickHouse can't carry the managed clause — never auto-inject or
+ // remove. Selected panels still get an editable row defaulting to the
+ // current text, unless the query already references the variable.
+ if (!selected.has(panelId)) {
+ return;
+ }
+ const ref = envelopeReferenceText(envelope);
+ if (!ref) {
+ return;
+ }
+ if (
+ textContainsVariableReference(ref.text, injectName) ||
+ textContainsVariableReference(ref.text, matchName)
+ ) {
+ return;
+ }
+ pushUsage(ref.kind, ref.text, ref.text);
+ });
+ });
+
+ return usages;
+}
+
+// Cheap yes/no check for the "Apply to all" disabled state: does every panel query
+// already reference the variable? Plain string checks — no ANTLR, no rewriting.
+export function isVariableAppliedToAllPanels(
+ dashboard: DashboardtypesGettableDashboardV2DTO,
+ attribute: string,
+ variableName: string,
+): boolean {
+ if (!attribute || !variableName) {
+ return false;
+ }
+ const clause = `${attribute} IN $${variableName}`;
+ const panels = dashboard.spec.panels ?? {};
+ return Object.values(panels).every((panel) => {
+ const queries = panel?.spec?.queries;
+ if (!queries?.length) {
+ return true;
+ }
+ return toQueryEnvelopes(queries).every((envelope) => {
+ if (envelope.type === 'builder_query') {
+ const spec = envelope.spec as
+ | { filter?: { expression?: string } }
+ | undefined;
+ return (spec?.filter?.expression ?? '').includes(clause);
+ }
+ const ref = envelopeReferenceText(envelope);
+ return ref ? textContainsVariableReference(ref.text, variableName) : true;
+ });
+ });
+}