Compare commits

...

4 Commits

Author SHA1 Message Date
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
8 changed files with 154 additions and 43 deletions

View File

@@ -169,6 +169,15 @@ 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.each([EQueryType.PROM, EQueryType.CLICKHOUSE, undefined])(
'is false when the query type is %s (not the builder)',
(queryType) => {

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,6 +104,7 @@ function renderItems(): void {
describe('useDrilldownDashboardVariables', () => {
beforeEach(() => {
mockIsEditable = true;
jest.clearAllMocks();
mockVariables = [];
mockSelectionMap = {};
@@ -171,6 +179,17 @@ 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([]);
expect(result.current.hasFieldVariables).toBe(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]);

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,7 +45,7 @@ export interface DrilldownVariableAction {
}
export interface UseDrilldownDashboardVariablesApi {
/** Whether the clicked point exposes any field to bind to a variable (gates the base-menu entry). */
/** Whether the submenu has any entry to offer (gates the base-menu entry). */
hasFieldVariables: boolean;
/** Resolved menu entries, one per group-by field on the clicked point. */
actions: DrilldownVariableAction[];
@@ -74,6 +75,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 +144,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 +204,5 @@ export function useDrilldownDashboardVariables({
],
);
return { hasFieldVariables: fieldVariables.length > 0, actions };
return { hasFieldVariables: actions.length > 0, 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

@@ -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,29 @@ 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 now = selectionRef.current[name];
const moved = base && now ? !areSelectionsEqual(base, now) : base !== now;
if (moved) {
delete fills[name];
}
});
const names = Object.keys(fills);
if (names.length === 0 || !dashboardId) {
return;
@@ -146,6 +163,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 ?? [])
);
}