diff --git a/.changeset/single-select-dashboard-filters.md b/.changeset/single-select-dashboard-filters.md new file mode 100644 index 0000000000..150f0458cc --- /dev/null +++ b/.changeset/single-select-dashboard-filters.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/api': patch +'@hyperdx/app': patch +--- + +feat: Allow configuring dashboard filters as single-select diff --git a/packages/api/openapi.json b/packages/api/openapi.json index 3c23e41201..1ac293d77f 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -3504,6 +3504,14 @@ "default": false, "description": "Widens a required filter's block to every tile on the dashboard. False\n(the default) blocks only the tiles that read the filter: those\nreferencing its variableName, and those its broadcast applies to.\nIgnored unless minSelections is 1.\n", "example": true + }, + "maxSelections": { + "type": "integer", + "enum": [ + 1 + ], + "description": "Maximum number of values that can be selected at once. Set to 1 to make\nthe filter single-select. Omit the field for the default multi-select\nbehavior.\n", + "example": 1 } } }, @@ -3586,6 +3594,14 @@ "default": false, "description": "Widens a required filter's block to every tile on the dashboard. False\n(the default) blocks only the tiles that read the filter: those\nreferencing its variableName, and those its broadcast applies to.\nIgnored unless minSelections is 1.\n", "example": true + }, + "maxSelections": { + "type": "integer", + "enum": [ + 1 + ], + "description": "Maximum number of values that can be selected at once. Set to 1 to make\nthe filter single-select. Omit the field for the default multi-select\nbehavior.\n", + "example": 1 } } }, @@ -3671,6 +3687,14 @@ "default": false, "description": "Widens a required filter's block to every tile on the dashboard. False\n(the default) blocks only the tiles that read the filter: those\nreferencing its variableName, and those its broadcast applies to.\nIgnored unless minSelections is 1.\n", "example": true + }, + "maxSelections": { + "type": "integer", + "enum": [ + 1 + ], + "description": "Maximum number of values that can be selected at once. Set to 1 to make\nthe filter single-select. Omit the field for the default multi-select\nbehavior.\n", + "example": 1 } } }, diff --git a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts index bf5d34f0ec..c4a82f7460 100644 --- a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts @@ -2709,6 +2709,47 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { } }); + it('round-trips a single-select filter through create and get', async () => { + const sourceId = ctx.traceSource._id.toString(); + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'Single-select filter', + tiles: [traceTile(sourceId)], + filters: [queryFilter({ maxSelections: 1 })], + }, + ); + expect(createResult.isError).toBeFalsy(); + const created = JSON.parse(getFirstText(createResult)); + expect(created.filters[0].maxSelections).toBe(1); + + const getResult = await callTool( + ctx.client!, + 'clickstack_get_dashboard', + { id: created.id }, + ); + expect( + JSON.parse(getFirstText(getResult)).filters[0].maxSelections, + ).toBe(1); + }); + + it.each([0, 2])('rejects maxSelections %s', async value => { + const sourceId = ctx.traceSource._id.toString(); + const result = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'Bad maxSelections', + tiles: [traceTile(sourceId)], + filters: [queryFilter({ maxSelections: value })], + }, + ); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain('maxSelections'); + }); + it.each([2, -1, 1.5])('rejects minSelections %s', async value => { const sourceId = ctx.traceSource._id.toString(); const result = await callTool( diff --git a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts index 75c833c601..6d3bcc42bf 100644 --- a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts @@ -128,6 +128,35 @@ describe('resolveDashboardVariables', () => { expect(resolved.error).toContain('Available variables: (none)'); }); + it('rejects several values for a single-select variable', () => { + const resolved = resolveDashboardVariables( + [staticFilter({ maxSelections: 1 })], + [{ name: 'env', values: ['prod', 'staging'] }], + ); + + if (!('error' in resolved)) throw new Error('expected an error'); + expect(resolved.error).toContain('"env"'); + expect(resolved.error).toContain('single-select'); + }); + + it('applies one value to a single-select variable', () => { + expect( + resolveDashboardVariables( + [staticFilter({ maxSelections: 1 })], + [{ name: 'env', values: ['prod'] }], + ), + ).toEqual({ + variables: [ + { + name: 'env', + expression: undefined, + values: ['prod'], + maxSelections: 1, + }, + ], + }); + }); + it('declares a variable for a static filter', () => { expect(resolveDashboardVariables([staticFilter()], undefined)).toEqual({ variables: [{ name: 'env', expression: undefined, values: [] }], diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index a35dfff614..934902e8d3 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -118,6 +118,8 @@ Apply these before calling clickstack_save_dashboard. Each rule is enforced by t 9e. MAKE A FILTER REQUIRED ONLY WHEN AN UNSCOPED VIEW IS MEANINGLESS. minSelections: 1 blocks the tiles that read the filter - the ones referencing its $variableName, and the ones its broadcast applies to - until the user picks a value. isGlobalRequirement: true widens that to every tile on the dashboard. Consider pairing either form with savedFilterValues so the dashboard opens on a sensible default rather than blocked. +9f. MAKE A FILTER SINGLE-SELECT WHEN A TILE ONLY MAKES SENSE FOR ONE VALUE. maxSelections: 1 limits the dropdown to one value at a time, for example a host picker feeding a per-host detail view. + 10. UPDATE IS REPLACE, NOT MERGE. clickstack_save_dashboard with an id overwrites tiles, containers, and filters in their entirety. Call clickstack_get_dashboard first when you only want to add or rename one entry; do not send a partial set or you will silently drop everything you omitted. 11. GROUP RELATED TILES INTO CONTAINERS. REQUIRED at five or more tiles, no exceptions. An ungrouped wall of nine or ten tiles is a readability failure even when each tile is correct in isolation. Containers are the right way to introduce structure; markdown tiles for section labels are not. diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index b0a2063e7a..02522a2bcd 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -1319,6 +1319,16 @@ const mcpDashboardFilterBaseShape = { 'Widens a REQUIRED filter (minSelections: 1) to block EVERY tile on the dashboard, ' + 'not just the ones that read it. Ignored unless minSelections is 1.', ), + maxSelections: z + .number() + .int() + .min(1) + .max(1) + .optional() + .describe( + 'Set to 1 to make this filter SINGLE-SELECT: the user can pick at most one ' + + 'value. Omit for the normal multi-select behavior.', + ), }; const mcpQueryExpressionFilterSchema = z diff --git a/packages/api/src/mcp/tools/dashboards/variables.ts b/packages/api/src/mcp/tools/dashboards/variables.ts index 832f8d2ae0..64a6a1678d 100644 --- a/packages/api/src/mcp/tools/dashboards/variables.ts +++ b/packages/api/src/mcp/tools/dashboards/variables.ts @@ -2,6 +2,7 @@ import { getDashboardVariableDeclarations, getDashboardVariableFilters, getFilterVariableName, + isFilterSingleSelect, isFilterVariableEnabled, isStaticListFilter, } from '@hyperdx/common-utils/dist/filters'; @@ -101,6 +102,23 @@ export function resolveDashboardVariables( return { error: optionErrors.join('\n') }; } + // The dashboard can never hold several values for a single-select variable. + const singleSelectNames = new Set( + variables.filter(isFilterSingleSelect).map(variable => variable.name), + ); + const singleSelectErrors = variableValues + .filter( + ({ name, values }) => values.length > 1 && singleSelectNames.has(name), + ) + .map( + ({ name }) => + `Variable "${name}" belongs to a single-select filter (maxSelections: 1) ` + + 'and accepts at most one value.', + ); + if (singleSelectErrors.length > 0) { + return { error: singleSelectErrors.join('\n') }; + } + // Override the default empty selection with the given variableValues for (const { name, values } of variableValues) { byName.get(name)!.values = values; diff --git a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts index 5c3d44697e..dcaf898cd5 100644 --- a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts +++ b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts @@ -1210,6 +1210,27 @@ describe('dashboard router', () => { .expect(400); }); + it('persists maxSelections on create', async () => { + const filter = makeFilter({ maxSelections: 1 }); + + const created = await agent + .post('/dashboards') + .send({ ...MOCK_DASHBOARD, filters: [filter] }) + .expect(200); + + expect(created.body.filters).toEqual([filter]); + }); + + it.each([0, 2, 1.5, '1'])('rejects maxSelections %s', async value => { + await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + filters: [makeFilter({ maxSelections: value })], + }) + .expect(400); + }); + it('persists a dashboard-wide requirement', async () => { const filter = makeFilter({ minSelections: 1, diff --git a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts index 59f5e2625c..cdaa214268 100644 --- a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts @@ -6117,6 +6117,37 @@ describe('External API v2 Dashboards - new format', () => { }); }); + describe('single-select filters', () => { + const variants = [ + ['QUERY_EXPRESSION', filterInput], + ['STATIC_LIST', staticFilterInput], + ['PROMETHEUS_LABEL', promqlFilterInput], + ] as const; + + it.each(variants)( + 'accepts a single-select %s filter', + async (_type, makeFilter) => { + const response = await sendFilters([ + makeFilter({ maxSelections: 1 }), + ]); + expect(response.status).toBe(200); + expect(response.body.data.filters[0].maxSelections).toBe(1); + }, + ); + + it('omits the key from responses for a multi-select filter', async () => { + const response = await sendFilters([filterInput()]); + expect(response.status).toBe(200); + expect(response.body.data.filters[0]).not.toHaveProperty( + 'maxSelections', + ); + }); + + it.each([0, 2, 1.5, '1'])('rejects maxSelections %s', async value => { + await expectFilters([filterInput({ maxSelections: value })], 400); + }); + }); + describe('static-list filters', () => { it('accepts a static-list filter and round-trips it through GET', async () => { const response = await sendFilters([staticFilterInput()]); diff --git a/packages/api/src/routers/external-api/v2/dashboards.ts b/packages/api/src/routers/external-api/v2/dashboards.ts index 01f40b632a..1b221b19ce 100644 --- a/packages/api/src/routers/external-api/v2/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/dashboards.ts @@ -2055,6 +2055,14 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * referencing its variableName, and those its broadcast applies to. * Ignored unless minSelections is 1. * example: true + * maxSelections: + * type: integer + * enum: [1] + * description: | + * Maximum number of values that can be selected at once. Set to 1 to make + * the filter single-select. Omit the field for the default multi-select + * behavior. + * example: 1 * * StaticListFilterInput: * type: object @@ -2141,6 +2149,14 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * referencing its variableName, and those its broadcast applies to. * Ignored unless minSelections is 1. * example: true + * maxSelections: + * type: integer + * enum: [1] + * description: | + * Maximum number of values that can be selected at once. Set to 1 to make + * the filter single-select. Omit the field for the default multi-select + * behavior. + * example: 1 * * PrometheusLabelFilterInput: * type: object @@ -2228,6 +2244,14 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * referencing its variableName, and those its broadcast applies to. * Ignored unless minSelections is 1. * example: true + * maxSelections: + * type: integer + * enum: [1] + * description: | + * Maximum number of values that can be selected at once. Set to 1 to make + * the filter single-select. Omit the field for the default multi-select + * behavior. + * example: 1 * * Filter: * allOf: diff --git a/packages/app/src/DashboardFilters.tsx b/packages/app/src/DashboardFilters.tsx index 1eb89262bf..9242b71e61 100644 --- a/packages/app/src/DashboardFilters.tsx +++ b/packages/app/src/DashboardFilters.tsx @@ -6,6 +6,7 @@ import { getPendingFilterValuesVariables, isFilterGlobalRequirement, isFilterRequired, + isFilterSingleSelect, isFilterVariableEnabled, isQueryExpressionFilter, isStaticListFilter, @@ -186,6 +187,7 @@ const DashboardFilterSelect = ({ loading={isLoading} // A static list renders in the order its author wrote it. sort={!isStaticListFilter(filter)} + isMultiSelect={!isFilterSingleSelect(filter)} onChange={onChange} data-testid={`dashboard-filter-select-${filter.name}`} /> diff --git a/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx index eb97db3f19..6e2d194412 100644 --- a/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx @@ -255,6 +255,14 @@ export const DashboardFilterEditForm = ({ {showRequiredFilterOptions && ( + { expect(screen.getByTestId('filter-required-checkbox')).toBeChecked(); }); + it('saves a single-select filter and reopens it checked', async () => { + const { onSaveFilter, user } = renderModal(); + + await user.click(screen.getByTestId('add-filter-button')); + await selectFilterType(user, 'Static values'); + await user.type(screen.getByTestId('filter-name-input'), 'Environment'); + await user.type(screen.getByTestId('filter-options-input'), 'prod{Enter}'); + await user.click(screen.getByTestId('filter-single-select-checkbox')); + await user.click(screen.getByTestId('save-filter-button')); + + await waitFor(() => expect(onSaveFilter).toHaveBeenCalledTimes(1)); + const saved: DashboardFilter = onSaveFilter.mock.calls[0][0]; + expect(saved.maxSelections).toBe(1); + expect(saved.minSelections).toBeUndefined(); + + renderModal({ filters: [saved] }); + await user.click( + screen.getAllByTestId(`edit-filter-button-${saved.name}`)[0], + ); + + expect(screen.getByTestId('filter-single-select-checkbox')).toBeChecked(); + }); + it('offers the requirement scope, unchecked, once the filter is required', async () => { const { user } = renderModal(); diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts index 718c0e6b4e..fac8468393 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts @@ -298,3 +298,41 @@ describe('isGlobalRequirement', () => { }, ); }); + +describe('maxSelections', () => { + it.each(variants)( + 'round-trips single-select on a %s filter', + (_type, filter) => { + const saved = toSavedFilter( + formValues({ ...filter, isSingleSelect: true }), + ); + + expect(saved.maxSelections).toBe(1); + expect(saved).not.toHaveProperty('isSingleSelect'); + expect(toFormValues(saved).isSingleSelect).toBe(true); + }, + ); + + it.each(variants)( + 'emits no key at all for a multi-select %s filter', + (_type, filter) => { + const saved = toSavedFilter( + formValues({ ...filter, isSingleSelect: false }), + ); + + expect(saved).not.toHaveProperty('maxSelections'); + expect(toFormValues(saved).isSingleSelect).toBe(false); + }, + ); + it('keeps both limits on a filter that is single-select and required', () => { + const saved = toSavedFilter( + formValues({ + ...byType.STATIC_LIST, + isSingleSelect: true, + isRequired: true, + }), + ); + + expect(saved).toMatchObject({ minSelections: 1, maxSelections: 1 }); + }); +}); diff --git a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts index d47610d385..94da455c08 100644 --- a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts +++ b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts @@ -4,6 +4,7 @@ import { isFilterBroadcastEnabled, isFilterGlobalRequirement, isFilterRequired, + isFilterSingleSelect, isFilterVariableEnabled, } from '@hyperdx/common-utils/dist/filters'; import { @@ -27,9 +28,11 @@ export type FilterFormValues = { isRequired: boolean; /** Always set, unlike the stored field, whose default lives in `isFilterGlobalRequirement`. */ isGlobalRequirement: boolean; + /** Boolean version of the persisted numeric `maxSelections`. */ + isSingleSelect: boolean; } & Omit< QueryExpressionDashboardFilter, - 'type' | 'minSelections' | 'isGlobalRequirement' + 'type' | 'minSelections' | 'isGlobalRequirement' | 'maxSelections' > & Omit< StaticListDashboardFilter, @@ -38,6 +41,7 @@ export type FilterFormValues = { | 'isVariableEnabled' | 'minSelections' | 'isGlobalRequirement' + | 'maxSelections' > & Omit< PromqlLabelDashboardFilter, @@ -46,6 +50,7 @@ export type FilterFormValues = { | 'isVariableEnabled' | 'minSelections' | 'isGlobalRequirement' + | 'maxSelections' >; export type FilterFormControl = Control; @@ -67,6 +72,7 @@ export const toFormValues = ( isVariableEnabled: filter ? isFilterVariableEnabled(filter) : false, isRequired: filter ? isFilterRequired(filter) : false, isGlobalRequirement: filter ? isFilterGlobalRequirement(filter) : false, + isSingleSelect: filter ? isFilterSingleSelect(filter) : false, // QUERY_EXPRESSION fields expression: queried?.expression ?? '', @@ -87,14 +93,17 @@ export const toFormValues = ( /** Normalizes the form values into the filter that gets stored. */ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { - // Pulled out of the spread below so neither key is stored unless it's relevant - const { isRequired, isGlobalRequirement, ...rest } = values; - const requirement = isRequired - ? { - minSelections: 1, - ...(isGlobalRequirement ? { isGlobalRequirement: true } : {}), - } - : {}; + // Pulled out of the spread below so no key is stored unless it's relevant + const { isRequired, isGlobalRequirement, isSingleSelect, ...rest } = values; + const selectionLimits = { + ...(isRequired + ? { + minSelections: 1, + ...(isGlobalRequirement ? { isGlobalRequirement: true } : {}), + } + : {}), + ...(isSingleSelect ? { maxSelections: 1 } : {}), + }; if (values.type === 'STATIC_LIST') { return DashboardFilterSchema.parse({ @@ -103,7 +112,7 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { isBroadcastEnabled: false, isVariableEnabled: true, variableName: getFilterVariableName(values), - ...requirement, + ...selectionLimits, }); } @@ -115,7 +124,7 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { isBroadcastEnabled: false, isVariableEnabled: true, variableName: getFilterVariableName(values), - ...requirement, + ...selectionLimits, }); } @@ -131,6 +140,6 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { isBroadcastEnabled: isFilterBroadcastEnabled(values), isVariableEnabled, variableName: isVariableEnabled ? getFilterVariableName(values) : undefined, - ...requirement, + ...selectionLimits, }); }; diff --git a/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.tsx b/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.tsx index ff3f9d07ca..ad5ae3d4d7 100644 --- a/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.tsx +++ b/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.tsx @@ -26,6 +26,7 @@ type VirtualMultiSelectProps = { placeholder?: string; /** Whether to sort options before rendering. True by default */ sort?: boolean; + isMultiSelect?: boolean; values: string[]; onChange: (values: string[]) => void; 'data-testid'?: string; @@ -37,6 +38,7 @@ export function VirtualMultiSelect({ loading, placeholder, sort = true, + isMultiSelect = true, values, onChange, 'data-testid': dataTestId, @@ -72,13 +74,6 @@ export function VirtualMultiSelect({ }, }); - const handleSelectValue = (val: string) => { - onChange( - values.includes(val) ? values.filter(v => v !== val) : [...values, val], - ); - setSearch(''); - }; - const handleRemoveValue = (val: string) => onChange(values.filter(v => v !== val)); @@ -86,10 +81,20 @@ export function VirtualMultiSelect({ const handleAddValue = (val: string) => { if (!values.includes(val)) { - onChange([...values, val]); + onChange(isMultiSelect ? [...values, val] : [val]); } }; + const handleSelectValue = (val: string) => { + if (values.includes(val)) { + handleRemoveValue(val); + } else { + handleAddValue(val); + } + setSearch(''); + if (!isMultiSelect) combobox.closeDropdown(); + }; + const handleKeyDown: KeyboardEventHandler = event => { if (event.key === 'Backspace' && search.length === 0 && values.length > 0) { event.preventDefault(); @@ -116,6 +121,10 @@ export function VirtualMultiSelect({ setSearch(event.currentTarget.value); }; + // Hide the input field (cursor) for single selects with existing values, + // otherwise the user is visually encouraged to add another value. + const isInputFieldLocked = !isMultiSelect && values.length > 0; + const virtualItems = virtualizer.getVirtualItems(); const totalSize = virtualizer.getTotalSize(); @@ -167,6 +176,8 @@ export function VirtualMultiSelect({ combobox.openDropdown()} onBlur={() => combobox.closeDropdown()} + type={isInputFieldLocked ? 'hidden' : 'visible'} + readOnly={isInputFieldLocked} value={search} placeholder={placeholder} onChange={handleChange} diff --git a/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx b/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx index ec0d06fb6f..b3f9fffc39 100644 --- a/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx +++ b/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx @@ -941,6 +941,53 @@ describe('useDashboardFilters', () => { }); }); + describe('single-select filters', () => { + const singleSelect: QueryExpressionDashboardFilter = { + ...mockFilters[0], + isVariableEnabled: true, + variableName: 'env', + maxSelections: 1, + }; + + it('honors only the first of several values in the URL', () => { + mockState = [ + { type: 'variable', name: 'env', values: ['staging', 'prod'] }, + ]; + + const { result } = renderHook(() => useDashboardFilters([singleSelect])); + + expect(selectionFor(result, 'filter1')?.included).toEqual( + new Set(['staging']), + ); + expect(result.current.variables).toEqual([ + { + name: 'env', + expression: 'environment', + values: ['staging'], + maxSelections: 1, + }, + ]); + }); + + it('drops the extra values from the URL on the next write', () => { + mockState = [ + { type: 'variable', name: 'env', values: ['staging', 'prod'] }, + ]; + const filters = [singleSelect, mockFilters[1]]; + + const { result } = renderHook(() => useDashboardFilters(filters)); + + act(() => { + result.current.setFilterValue('filter2', ['api']); + }); + + expect(mockState).toEqual([ + { type: 'sql', condition: "service.name IN ('api')" }, + { type: 'variable', name: 'env', values: ['staging'] }, + ]); + }); + }); + describe('unsatisfiedRequiredFilters', () => { const required = ( overrides: Partial = {}, diff --git a/packages/app/src/hooks/useDashboardFilters.tsx b/packages/app/src/hooks/useDashboardFilters.tsx index a91ed71180..22a2dc5f7d 100644 --- a/packages/app/src/hooks/useDashboardFilters.tsx +++ b/packages/app/src/hooks/useDashboardFilters.tsx @@ -183,6 +183,7 @@ const useDashboardFilters = (filters: DashboardFilter[]) => { values: selection ? Array.from(selection.included).map(String).sort() : [], + maxSelections: filter.maxSelections, }; }, ); diff --git a/packages/app/tests/e2e/features/dashboard-filter-value-format.spec.ts b/packages/app/tests/e2e/features/dashboard-filter-value-format.spec.ts index e6fe10b81f..5311b95f2b 100644 --- a/packages/app/tests/e2e/features/dashboard-filter-value-format.spec.ts +++ b/packages/app/tests/e2e/features/dashboard-filter-value-format.spec.ts @@ -13,25 +13,10 @@ * Every test is `@full-stack`: the variables flag is only set on the full-stack * webServer (see playwright.config.ts). */ -import type { Page } from '@playwright/test'; - import { DashboardPage } from '../page-objects/DashboardPage'; import { expect, test } from '../utils/base-test'; import { DEFAULT_LOGS_SOURCE_NAME } from '../utils/constants'; -import { expectFiltersParam, type FilterEntry } from '../utils/filters-param'; - -/** Navigate to a dashboard with a hand-written `filters=` param. */ -const gotoWithFilters = async ( - page: Page, - dashboardId: string, - entries: FilterEntry[], -) => { - await page.goto( - `/dashboards/${dashboardId}?filters=${encodeURIComponent( - JSON.stringify(entries), - )}`, - ); -}; +import { expectFiltersParam, gotoWithFilters } from '../utils/filters-param'; /** Assert exactly `values` are selected in `filterName`'s multi-select. */ const expectSelected = async ( diff --git a/packages/app/tests/e2e/features/dashboard-single-select-filters.spec.ts b/packages/app/tests/e2e/features/dashboard-single-select-filters.spec.ts new file mode 100644 index 0000000000..be1ca6c9f8 --- /dev/null +++ b/packages/app/tests/e2e/features/dashboard-single-select-filters.spec.ts @@ -0,0 +1,98 @@ +/** + * A dashboard filter marked single-select (`maxSelections: 1`) holds at most one + * value: picking another value replaces the selection, typing is ignored while + * a value is selected, and a `filters=` URL param carrying several values keeps + * only the first. + */ +import { DashboardPage } from '../page-objects/DashboardPage'; +import { expect, test } from '../utils/base-test'; +import { DEFAULT_LOGS_SOURCE_NAME } from '../utils/constants'; +import { expectFiltersParam, gotoWithFilters } from '../utils/filters-param'; + +const ENVIRONMENTS = ['prod', 'staging', 'dev']; + +test.describe( + 'Single-select dashboard filters', + { tag: ['@dashboard', '@full-stack'] }, + () => { + let dashboardPage: DashboardPage; + + test.beforeEach(async ({ page }) => { + dashboardPage = new DashboardPage(page); + await dashboardPage.goto(); + await dashboardPage.createNewDashboard(); + await dashboardPage.addNumberTile('Count tile', DEFAULT_LOGS_SOURCE_NAME); + await dashboardPage.openEditFiltersModal(); + await dashboardPage.addStaticListFilterToDashboard( + 'Environment', + ENVIRONMENTS, + { variableName: 'env', singleSelect: true }, + ); + await dashboardPage.closeFiltersModal(); + }); + + test('replaces the selection when another value is picked', async ({ + page, + }) => { + await dashboardPage.openFilterDropdown('Environment'); + await dashboardPage.getFilterOption('prod').click(); + await expect( + dashboardPage.getFilterPill('Environment', 'prod'), + ).toBeVisible(); + await expectFiltersParam(page, [ + { type: 'variable', name: 'env', values: ['prod'] }, + ]); + + await dashboardPage.openFilterDropdown('Environment'); + await dashboardPage.getFilterOption('staging').click(); + await expect( + dashboardPage.getFilterPill('Environment', 'staging'), + ).toBeVisible(); + await expect( + dashboardPage.getFilterPill('Environment', 'prod'), + ).toHaveCount(0); + await expectFiltersParam(page, [ + { type: 'variable', name: 'env', values: ['staging'] }, + ]); + }); + + test('ignores typing while a value is selected', async ({ page }) => { + await dashboardPage.openFilterDropdown('Environment'); + await dashboardPage.getFilterOption('prod').click(); + await expect( + dashboardPage.getFilterPill('Environment', 'prod'), + ).toBeVisible(); + + await dashboardPage.openFilterDropdown('Environment'); + await expect( + dashboardPage.getFilterSearchInput('Environment'), + ).toBeFocused(); + await page.keyboard.type('qa'); + await expect( + dashboardPage.getFilterSearchInput('Environment'), + ).toHaveValue(''); + await expect( + dashboardPage.getFilterPill('Environment', 'prod'), + ).toBeVisible(); + await expectFiltersParam(page, [ + { type: 'variable', name: 'env', values: ['prod'] }, + ]); + }); + + test('keeps only the first of several values in the URL', async ({ + page, + }) => { + await gotoWithFilters(page, dashboardPage.getCurrentDashboardId(), [ + { type: 'variable', name: 'env', values: ['dev', 'prod'] }, + ]); + await dashboardPage.waitForLoaded(); + + await expect( + dashboardPage.getFilterPill('Environment', 'dev'), + ).toBeVisible(); + await expect( + dashboardPage.getFilterPill('Environment', 'prod'), + ).toHaveCount(0); + }); + }, +); diff --git a/packages/app/tests/e2e/page-objects/DashboardPage.ts b/packages/app/tests/e2e/page-objects/DashboardPage.ts index 18083a67a3..b72a03b77c 100644 --- a/packages/app/tests/e2e/page-objects/DashboardPage.ts +++ b/packages/app/tests/e2e/page-objects/DashboardPage.ts @@ -107,6 +107,7 @@ export class DashboardPage { readonly variableEnabledCheckbox: Locator; readonly requiredFilterCheckbox: Locator; readonly globalRequirementCheckbox: Locator; + readonly singleSelectCheckbox: Locator; readonly variableNameInput: Locator; private readonly saveButton: Locator; private readonly tileSourceSelector: Locator; @@ -173,6 +174,9 @@ export class DashboardPage { this.globalRequirementCheckbox = page.getByTestId( 'filter-global-requirement-checkbox', ); + this.singleSelectCheckbox = page.getByTestId( + 'filter-single-select-checkbox', + ); this.variableNameInput = page.getByTestId('filter-variable-name-input'); this.saveButton = page.getByTestId('chart-save-button'); @@ -1416,7 +1420,10 @@ export class DashboardPage { async addStaticListFilterToDashboard( name: string, options: string[], - variableOptions?: { variableName?: string } & FilterRequirementOptions, + variableOptions?: { + variableName?: string; + singleSelect?: boolean; + } & FilterRequirementOptions, ) { await this.addFiltersButton.click(); await this.selectFilterType('Static values'); @@ -1427,6 +1434,9 @@ export class DashboardPage { if (variableOptions?.variableName !== undefined) { await this.variableNameInput.fill(variableOptions.variableName); } + if (variableOptions?.singleSelect !== undefined) { + await this.singleSelectCheckbox.setChecked(variableOptions.singleSelect); + } await this.setFilterRequirement(variableOptions); await this.page.getByTestId('save-filter-button').click(); await this.getFilterItemByName(name).waitFor({ diff --git a/packages/app/tests/e2e/utils/filters-param.ts b/packages/app/tests/e2e/utils/filters-param.ts index 7d09cb1d9e..17a26c7851 100644 --- a/packages/app/tests/e2e/utils/filters-param.ts +++ b/packages/app/tests/e2e/utils/filters-param.ts @@ -29,3 +29,16 @@ export const expectFiltersParam = async ( expect(filtersParam(page)).toEqual(expected); }).toPass({ timeout: 10000 }); }; + +/** Navigate to a dashboard with a hand-written `filters=` param. */ +export const gotoWithFilters = async ( + page: Page, + dashboardId: string, + entries: FilterEntry[], +) => { + await page.goto( + `/dashboards/${dashboardId}?filters=${encodeURIComponent( + JSON.stringify(entries), + )}`, + ); +}; diff --git a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts index c33ae79dfa..5b24b62f21 100644 --- a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts +++ b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts @@ -492,6 +492,38 @@ describe('dashboardFilterValues', () => { }); }); + describe('resolveFilterSelection for a single-select filter', () => { + it('keeps only the first value of a variable entry', () => { + const parsed = parseDashboardFilterValues([ + { type: 'variable', name: 'env', values: ['staging', 'prod'] }, + ]); + + expect( + resolveFilterSelection(staticFilter({ maxSelections: 1 }), parsed), + ).toEqual(included('staging')); + }); + + it('keeps only the first value of an expression entry', () => { + const parsed = parseDashboardFilterValues([ + { type: 'sql', condition: "ServiceName IN ('b', 'a')" }, + ]); + + expect( + resolveFilterSelection(filter({ maxSelections: 1 }), parsed), + ).toEqual(included('b')); + }); + + it('leaves a multi-select filter untouched', () => { + const parsed = parseDashboardFilterValues([ + { type: 'variable', name: 'env', values: ['staging', 'prod'] }, + ]); + + expect(resolveFilterSelection(staticFilter(), parsed)).toEqual( + included('staging', 'prod'), + ); + }); + }); + describe('getUnsatisfiedRequiredFilters', () => { const required = ( overrides: Partial = {}, diff --git a/packages/common-utils/src/__tests__/filters.test.ts b/packages/common-utils/src/__tests__/filters.test.ts index b853a2ff3c..4c79bedb7a 100644 --- a/packages/common-utils/src/__tests__/filters.test.ts +++ b/packages/common-utils/src/__tests__/filters.test.ts @@ -14,6 +14,7 @@ import { isFilterBroadcastEnabled, isFilterGlobalRequirement, isFilterRequired, + isFilterSingleSelect, isFilterVariableEnabled, isQueryExpressionFilter, isRenderablePinnedFilter, @@ -1684,6 +1685,16 @@ describe('filters', () => { }); }); + describe('isFilterSingleSelect', () => { + it('treats a missing cap as multi-select', () => { + expect(isFilterSingleSelect({})).toBe(false); + }); + + it('holds for a cap of one', () => { + expect(isFilterSingleSelect({ maxSelections: 1 })).toBe(true); + }); + }); + describe('isFilterGlobalRequirement', () => { it('treats a missing flag as covering only the tiles that read the filter', () => { expect(isFilterGlobalRequirement({})).toBe(false); @@ -1937,6 +1948,18 @@ describe('filters', () => { ).toEqual([{ name: 'svc', expression: 'ServiceName' }]); }); + it('carries the selection cap', () => { + expect( + getDashboardVariableDeclarations([ + filter({ + isVariableEnabled: true, + variableName: 'svc', + maxSelections: 1, + }), + ]), + ).toEqual([{ name: 'svc', expression: 'ServiceName', maxSelections: 1 }]); + }); + it('falls back to the name derived from the display name', () => { expect( getDashboardVariableDeclarations([ diff --git a/packages/common-utils/src/dashboardFilterValues.ts b/packages/common-utils/src/dashboardFilterValues.ts index fe71f4d08c..cd9c1da4e9 100644 --- a/packages/common-utils/src/dashboardFilterValues.ts +++ b/packages/common-utils/src/dashboardFilterValues.ts @@ -7,6 +7,7 @@ import { getFilterVariableName, isFilterGlobalRequirement, isFilterRequired, + isFilterSingleSelect, isFilterVariableEnabled, parseQuery, } from '@/filters'; @@ -150,6 +151,22 @@ export function resolveFilterSelection( parsed: Pick & { byVariable: ReadonlyMap; }, +): FilterSelection | undefined { + const selection = resolveUncappedFilterSelection(filter, parsed); + if (!selection || !isFilterSingleSelect(filter)) return selection; + if (selection.included.size <= 1) return selection; + + // State written before the filter became single-select (or by hand) can hold + // several values; only the first is honored. + const [first] = selection.included; + return { ...selection, included: new Set([first]) }; +} + +function resolveUncappedFilterSelection( + filter: DashboardFilter, + parsed: Pick & { + byVariable: ReadonlyMap; + }, ): FilterSelection | undefined { const key = filterSelectionKey(filter); if (key.kind === 'variable') { diff --git a/packages/common-utils/src/filters.ts b/packages/common-utils/src/filters.ts index 1f377675bd..e6c3c34048 100644 --- a/packages/common-utils/src/filters.ts +++ b/packages/common-utils/src/filters.ts @@ -855,6 +855,13 @@ export function isFilterRequired(filter: { minSelections?: number }): boolean { return (filter.minSelections ?? 0) > 0; } +/** Whether at most one value can be selected for the filter (or its variable). */ +export function isFilterSingleSelect(filter: { + maxSelections?: number; +}): boolean { + return filter.maxSelections === 1; +} + /** * Whether the given required filter blocks every tile on the dashboard, * rather than only the tiles that read it. @@ -959,7 +966,7 @@ export function getFilterVariableName(filter: { /** A dashboard variable's identity, before any selection is attached. */ export type DashboardVariableDeclaration = Pick< ChartVariable, - 'name' | 'expression' + 'name' | 'expression' | 'maxSelections' >; /** Minimal projection of fields necessary to extract the variables a dashboard declares. */ @@ -968,6 +975,7 @@ export type FilterForVariableDeclaration = { expression?: string; variableName?: string; isVariableEnabled?: boolean; + maxSelections?: number; }; /** @@ -1001,6 +1009,7 @@ export function getDashboardVariableDeclarations( return getDashboardVariableFilters(filters).map(({ filter, name }) => ({ name, expression: filter.expression, + maxSelections: filter.maxSelections, })); } diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index f895e15a37..1d2ab24e29 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -1717,6 +1717,8 @@ export const ChartVariableSchema = z.object({ expression: z.string().optional(), /** Empty means nothing is selected. */ values: z.array(z.string()), + /** The filter's selection cap; 1 means the variable is single-select. */ + maxSelections: z.number().optional(), }); export type ChartVariable = z.infer; @@ -2120,6 +2122,11 @@ const dashboardFilterBaseSchema = z.object({ * undefined and 0 both imply no minimum selection requirement. */ minSelections: z.number().int().min(0).max(1).optional(), + /** + * The most values that can be selected at once. Only 1 is currently allowed, + * which makes the filter single-select. undefined implies no cap. + */ + maxSelections: z.number().int().min(1).max(1).optional(), /** * Whether an unsatisfied requirement blocks every tile on the dashboard, * rather than only the tiles that read this filter (via variable or broadcast).