Compare commits

...

5 Commits

Author SHA1 Message Date
Abhi Kumar
bbf2fb4ec4 refactor(dashboard): address review on drilldown and variable seeding 2026-11-27 12:32:42 +05:30
Abhi Kumar
3ac1479cc3 fix(dashboard): count typed values when comparing variable selections
A seed that only adds the typed-value marker was skipped as unchanged, so a later reconcile
could still drop the value.
2026-11-26 16:15:39 +05:30
Abhi Kumar
a34b75f86d fix(dashboard): keep variable values a link or host sets
A custom variable keeps link-seeded values its list doesn't offer, as typed values. An auto-fill
computed before the seed landed no longer overwrites it a frame later.
2026-11-26 15:51:23 +05:30
Abhi Kumar
7339662720 fix(dashboard): offer drilldown Create var only on editable dashboards 2026-11-26 15:50:53 +05:30
Abhi Kumar
d1dd086cec fix(dashboard): skip drilldown on panels that draw only formulas
Formula series have no query to drill into, so a panel whose builder queries are all disabled
no longer offers the click or its tooltip hint.
2026-11-26 15:50:52 +05:30
9 changed files with 231 additions and 61 deletions

View File

@@ -15,13 +15,8 @@ const mockNavigate = jest.fn();
const mockGetBuilderQueries = jest.fn();
const mockGetPanelQueryType = jest.fn();
let mockResolved = { resolvedQuery: 'RESOLVED_QUERY', isResolving: false };
let mockDashboardVariables: {
hasFieldVariables: boolean;
actions: unknown[];
} = {
hasFieldVariables: true,
actions: [],
};
const SET_ACTION = { fieldName: 'service.name' };
let mockDashboardVariables: { actions: unknown[] } = { actions: [SET_ACTION] };
// Boundaries tested elsewhere / needing external context — mocked so this suite isolates
// useDrilldown's orchestration (gating, which menu shows, the View-modal handoff).
@@ -145,10 +140,7 @@ describe('useDrilldown', () => {
mockGetBuilderQueries.mockReturnValue([{ name: 'A' }]);
mockGetPanelQueryType.mockReturnValue(EQueryType.QUERY_BUILDER);
mockResolved = { resolvedQuery: 'RESOLVED_QUERY', isResolving: false };
mockDashboardVariables = {
hasFieldVariables: true,
actions: [],
};
mockDashboardVariables = { actions: [SET_ACTION] };
});
describe('enableDrillDown', () => {
@@ -169,6 +161,24 @@ describe('useDrilldown', () => {
expect(result.current.enableDrillDown).toBe(false);
});
it('is false when every builder query is disabled, leaving only formulas to draw', () => {
mockGetBuilderQueries.mockReturnValue([
{ name: 'A', disabled: true },
{ name: 'B', disabled: true },
]);
const { result } = renderHook(() => useDrilldown(tsPanel, 'p1'));
expect(result.current.enableDrillDown).toBe(false);
});
it('is true when at least one builder query is enabled', () => {
mockGetBuilderQueries.mockReturnValue([
{ name: 'A', disabled: true },
{ name: 'B' },
]);
const { result } = renderHook(() => useDrilldown(tsPanel, 'p1'));
expect(result.current.enableDrillDown).toBe(true);
});
it.each([EQueryType.PROM, EQueryType.CLICKHOUSE, undefined])(
'is false when the query type is %s (not the builder)',
(queryType) => {
@@ -266,7 +276,7 @@ describe('useDrilldown', () => {
});
it('hides the Dashboard Variables entry when there are no group-by fields', () => {
mockDashboardVariables = { hasFieldVariables: false, actions: [] };
mockDashboardVariables = { actions: [] };
const { result } = renderHook(() => useDrilldown(tsPanel, 'p1'));
act(() =>
result.current.onPanelClick({

View File

@@ -18,6 +18,7 @@ let mockVariables: Array<{
let mockSelectionMap: Record<string, { value: unknown; allSelected: boolean }> =
{};
let mockIsEditable = true;
const mockSetVariableValue = jest.fn();
const mockPatchAsync = jest.fn().mockResolvedValue(undefined);
@@ -29,6 +30,12 @@ jest.mock('api/generated/services/dashboard', () => ({
data: { data: { spec: { variables: mockVariables } } },
}),
}));
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
() => ({
useDashboardEditContext: (): unknown => ({ isEditable: mockIsEditable }),
}),
);
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch',
() => ({
@@ -97,21 +104,22 @@ function renderItems(): void {
describe('useDrilldownDashboardVariables', () => {
beforeEach(() => {
mockIsEditable = true;
jest.clearAllMocks();
mockVariables = [];
mockSelectionMap = {};
});
it('hasFieldVariables reflects the clicked point group-by fields', () => {
it('offers an action per clicked point group-by field', () => {
const withFields = renderHook(() =>
useDrilldownDashboardVariables({ filters, onClose: jest.fn() }),
);
expect(withFields.result.current.hasFieldVariables).toBe(true);
expect(withFields.result.current.actions).toHaveLength(1);
const noFields = renderHook(() =>
useDrilldownDashboardVariables({ filters: [], onClose: jest.fn() }),
);
expect(noFields.result.current.hasFieldVariables).toBe(false);
expect(noFields.result.current.actions).toStrictEqual([]);
});
it('offers Set — writing an array for a multi-select var so the selector shows it', async () => {
@@ -171,6 +179,36 @@ describe('useDrilldownDashboardVariables', () => {
});
});
it('offers nothing to create on a dashboard the viewer cannot edit', () => {
mockVariables = [];
mockIsEditable = false;
const { result } = renderHook(() =>
useDrilldownDashboardVariables({ filters, onClose: jest.fn() }),
);
expect(result.current.actions).toStrictEqual([]);
});
it('still offers Set on a dashboard the viewer cannot edit', async () => {
mockVariables = [
{
name: 'svc',
dynamicAttribute: 'service.name',
multiSelect: true,
spec: { plugin: { kind: DYNAMIC_KIND } },
},
];
mockSelectionMap = { svc: { value: ['backend'], allSelected: false } };
mockIsEditable = false;
renderItems();
await userEvent.click(screen.getByTestId('drilldown-var-set'));
expect(mockSetVariableValue).toHaveBeenCalledWith('d1', 'svc', {
value: ['frontend'],
allSelected: false,
});
});
it('offers Create and persists a new dynamic variable when none matches', async () => {
mockVariables = [];
renderItems();

View File

@@ -87,14 +87,15 @@ export function useDrilldown(
const queries = panel.spec.queries;
// Drilldown only for builder-authored panels with a query to drill into (PromQL /
// ClickHouse have no builder context to refine).
// ClickHouse have no builder context to refine). A panel whose builder queries
// are all disabled draws only formulas, which have no series to drill into.
const enableDrillDown = useMemo(() => {
const queryType = getPanelQueryType(panel);
return (
getPanelDefinition(kind).actions.drilldown &&
!!queryType &&
isBuilderQueryType(queryType) &&
getBuilderQueries(queries).length > 0
getBuilderQueries(queries).some((query) => !query.disabled)
);
}, [kind, panel, queries]);
@@ -241,7 +242,7 @@ export function useDrilldown(
query={v1Query}
isResolving={isResolving}
links={panel.spec.links}
canSetDashboardVariables={dashboardVariables.hasFieldVariables}
canSetDashboardVariables={dashboardVariables.actions.length > 0}
onViewLogs={(): void => navigate('view_logs')}
onViewTraces={(): void => navigate('view_traces')}
onBreakout={openBreakout}
@@ -254,7 +255,6 @@ export function useDrilldown(
breakout.queryData,
breakout.onBreakout,
dashboardVariables.actions,
dashboardVariables.hasFieldVariables,
filter.isGroupColumnClick,
filter.onFilter,
context,

View File

@@ -12,6 +12,7 @@ import {
type VariableFormModel,
} from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableFormModel';
import { buildVariablesPatch } from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/utils/variablePatchOps';
import { useDashboardEditContext } from 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext';
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';
@@ -44,8 +45,6 @@ export interface DrilldownVariableAction {
}
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[];
}
@@ -74,6 +73,8 @@ export function useDrilldownDashboardVariables({
const selection = useDashboardStore(selectVariableValues(dashboardId));
const setVariableValue = useDashboardStore((state) => state.setVariableValue);
const { patchAsync } = useOptimisticPatch();
// Create writes the dashboard spec; Set/Unset only change this view's selection.
const { isEditable } = useDashboardEditContext();
const fieldVariables = useMemo<[string, string | number][]>(
() =>
@@ -141,51 +142,57 @@ export function useDrilldownDashboardVariables({
const actions = useMemo<DrilldownVariableAction[]>(
() =>
fieldVariables.map(([fieldName, fieldValue]) => {
const existing = dynamicVariables.find(
(v) => v.dynamicAttribute === fieldName,
);
if (!existing) {
fieldVariables
.map(([fieldName, fieldValue]) => {
const existing = dynamicVariables.find(
(v) => v.dynamicAttribute === fieldName,
);
if (!existing) {
if (!isEditable) {
return null;
}
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: DrilldownVariableActionKind.Create,
kind: isSame
? DrilldownVariableActionKind.Unset
: DrilldownVariableActionKind.Set,
onClick: (): void => {
void handleCreate(fieldName, fieldValue);
void logEvent(DashboardDetailEvents.DrilldownAction, {
action: 'setVariable',
dashboardId,
});
setSelection(existing.name, {
value: isSame ? cleared : assigned,
allSelected: false,
});
onClose();
},
};
}
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();
},
};
}),
})
.filter((action): action is DrilldownVariableAction => action !== null),
[
fieldVariables,
isEditable,
dynamicVariables,
selection,
setSelection,
@@ -195,5 +202,5 @@ export function useDrilldownDashboardVariables({
],
);
return { hasFieldVariables: fieldVariables.length > 0, actions };
return { actions };
}

View File

@@ -68,6 +68,49 @@ describe('useSeedVariableSelection', () => {
});
});
it('keeps URL values a custom list does not offer, as typed values', () => {
mockUrlValues = { ops: ['overflow_operation', 'GET /cart'] };
const dash = dashboard('d1', [
model({
name: 'ops',
type: 'CUSTOM',
multiSelect: true,
customValue: 'overflow_operation',
}),
]);
renderHook(() => useSeedVariableSelection(dash));
expect(seededValue('d1', 'ops')).toStrictEqual({
value: ['overflow_operation', 'GET /cart'],
allSelected: false,
customValues: ['GET /cart'],
});
});
it('marks typed URL values even when the store already holds them unmarked', () => {
useDashboardStore.getState().setVariableValues('d1', {
ops: { value: ['overflow_operation', 'GET /cart'], allSelected: false },
});
mockUrlValues = { ops: ['overflow_operation', 'GET /cart'] };
const dash = dashboard('d1', [
model({
name: 'ops',
type: 'CUSTOM',
multiSelect: true,
customValue: 'overflow_operation',
}),
]);
renderHook(() => useSeedVariableSelection(dash));
expect(seededValue('d1', 'ops')).toStrictEqual({
value: ['overflow_operation', 'GET /cart'],
allSelected: false,
customValues: ['GET /cart'],
});
});
it('falls back to the stored value when the URL has no entry', () => {
useDashboardStore
.getState()

View File

@@ -128,6 +128,47 @@ describe('useVariableSelection — setSelection', () => {
expect(svcCycleId()).toBe(before + 1);
});
it('drops an auto-fill when the selection moves before it flushes', async () => {
const { result } = renderHook(() => useVariableSelection(dashboard));
act(() => {
result.current.setSelection('env', { value: ['a'], allSelected: false });
});
act(() => {
result.current.autoSelect('env', { value: ['a', 'b'], allSelected: false });
});
act(() => {
result.current.setSelection('env', { value: ['c'], allSelected: false });
});
await act(async () => {
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
});
expect(useDashboardStore.getState().variableValues.d1?.env).toStrictEqual({
value: ['c'],
allSelected: false,
});
});
it('drops an auto-fill when the seed commits a first value before it flushes', async () => {
const { result } = renderHook(() => useVariableSelection(dashboard));
act(() => {
result.current.autoSelect('env', { value: ['a'], allSelected: false });
});
act(() => {
result.current.setSelection('env', { value: ['x'], allSelected: false });
});
await act(async () => {
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
});
expect(useDashboardStore.getState().variableValues.d1?.env).toStrictEqual({
value: ['x'],
allSelected: false,
});
});
it('still cascades a genuine change', () => {
const { result } = renderHook(() => useVariableSelection(dashboard));

View File

@@ -71,6 +71,15 @@ function fromUrlValue(
if (raw === ALL_SELECTED && model.multiSelect && model.showAllOption) {
return { value: null, allSelected: true };
}
// Values a link carries that the custom list doesn't offer were typed by whoever
// made it (or set by a host page); keep them as typed instead of dropping them.
if (model.type === 'CUSTOM' && model.multiSelect && Array.isArray(raw)) {
const options = knownVariableOptions(model);
const customValues = raw.map(String).filter((v) => !options.includes(v));
if (customValues.length > 0) {
return { value: raw, allSelected: false, customValues };
}
}
return { value: raw, allSelected: false };
}

View File

@@ -119,12 +119,30 @@ export function useVariableSelection(
// store write + one `enqueueDescendantsBatch` means dependents re-fetch once
// with the settled parent values, instead of once per fill.
const pendingAutoFillRef = useRef<VariableSelectionMap>({});
// The selection each pending fill was computed from.
const pendingAutoFillBaseRef = useRef<
Record<string, VariableSelection | undefined>
>({});
const autoFillFrameRef = useRef<number | null>(null);
const flushAutoFills = useCallback((): void => {
autoFillFrameRef.current = null;
const fills = pendingAutoFillRef.current;
const bases = pendingAutoFillBaseRef.current;
pendingAutoFillRef.current = {};
pendingAutoFillBaseRef.current = {};
// A fill reconciles the selection it saw. If that selection has moved since (the
// seed committed a typed value, the user picked one), the fill answers a question
// nobody is asking any more and would overwrite the newer value.
Object.keys(fills).forEach((name) => {
const base = bases[name];
const latest = selectionRef.current[name];
const hasSelectionMoved =
base && latest ? !areSelectionsEqual(base, latest) : base !== latest;
if (hasSelectionMoved) {
delete fills[name];
}
});
const names = Object.keys(fills);
if (names.length === 0 || !dashboardId) {
return;
@@ -146,6 +164,9 @@ export function useVariableSelection(
const autoSelect = useCallback(
(name: string, next: VariableSelection): void => {
if (!(name in pendingAutoFillBaseRef.current)) {
pendingAutoFillBaseRef.current[name] = selectionRef.current[name];
}
pendingAutoFillRef.current[name] = next;
if (autoFillFrameRef.current == null) {
autoFillFrameRef.current = requestAnimationFrame(flushAutoFills);

View File

@@ -237,13 +237,14 @@ function valueSetKey(value: SelectedVariableValue): string {
return list.map(String).sort().join('||');
}
/** True when two selections carry the same ALL flag and the same value set. */
/** True when two selections carry the same ALL flag, value set and typed values. */
export function areSelectionsEqual(
a: VariableSelection,
b: VariableSelection,
): boolean {
return (
!!a.allSelected === !!b.allSelected &&
valueSetKey(a.value) === valueSetKey(b.value)
valueSetKey(a.value) === valueSetKey(b.value) &&
valueSetKey(a.customValues ?? []) === valueSetKey(b.customValues ?? [])
);
}