diff --git a/.changeset/dashboard-filter-all-option-static-list.md b/.changeset/dashboard-filter-all-option-static-list.md new file mode 100644 index 000000000..ef49d0257 --- /dev/null +++ b/.changeset/dashboard-filter-all-option-static-list.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': minor +'@hyperdx/app': minor +'@hyperdx/common-utils': minor +--- + +feat: add an "All" option to static list dashboard filters. Turn on "Include "All" option" in the filter's settings, and its dropdown offers "All", which selects every option. With "All" selected, `$variable` and `$__filter` use every option and `$__conditionalAll` expands to `1=1`, matching Grafana. The external API and MCP accept `allowAll` on static list filters and `all: true` on saved filter values. diff --git a/packages/api/openapi.json b/packages/api/openapi.json index 02985bfd2..762edf333 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -1029,6 +1029,14 @@ "example": [ "hdx-oss-dev-api" ] + }, + "all": { + "type": "boolean", + "enum": [ + true + ], + "description": "Set to true to select \"All\"; `values` is then ignored, so send an empty array. Only allowed for filters that set allowAll.\n", + "example": true } } }, @@ -4378,6 +4386,11 @@ "dev" ] }, + "allowAll": { + "type": "boolean", + "description": "Adds an \"All\" choice to the dropdown, which selects every option.\nOnly allowed on multi-select filters (not with maxSelections 1).\nWith \"All\" selected, `$variableName` and `$__filter` use every\noption, and `$__conditionalAll` expands to 1=1.\n", + "example": true + }, "isBroadcastEnabled": { "type": "boolean", "enum": [ 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 b750454e5..a6077e6b6 100644 --- a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts @@ -2638,6 +2638,33 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { }); }); + it('round-trips allowAll and a saved "all" value', async () => { + const sourceId = ctx.traceSource._id.toString(); + const allValue = { type: 'variable', name: 'env', values: [], all: true }; + + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'All option round-trip', + tiles: [traceTile(sourceId)], + filters: [staticFilter({ allowAll: true })], + savedFilterValues: [allValue], + }, + ); + expect(createResult.isError).toBeFalsy(); + const created = JSON.parse(getFirstText(createResult)); + + const getResult = await callTool( + ctx.client!, + 'clickstack_get_dashboard', + { id: created.id }, + ); + const fetched = JSON.parse(getFirstText(getResult)); + expect(fetched.filters[0].allowAll).toBe(true); + expect(fetched.savedFilterValues).toEqual([allValue]); + }); + describe('required filters', () => { const queryFilter = (overrides: Record = {}) => ({ type: 'QUERY_EXPRESSION' as const, diff --git a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts index d50a56e33..48e4de819 100644 --- a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts @@ -194,6 +194,34 @@ describe('resolveDashboardVariables', () => { }); }); + it('expands a simulated "All" to every option of a static filter', () => { + expect( + resolveDashboardVariables( + [staticFilter({ allowAll: true })], + [{ name: 'env', values: [], all: true }], + ), + ).toEqual({ + variables: [ + { + name: 'env', + expression: undefined, + values: ['dev', 'prod', 'staging'], + all: true, + }, + ], + }); + }); + + it('rejects a simulated "All" on a filter that does not offer it', () => { + const resolved = resolveDashboardVariables( + [staticFilter()], + [{ name: 'env', values: [], all: true }], + ); + + if (!('error' in resolved)) throw new Error('expected an error'); + expect(resolved.error).toContain('does not offer "All"'); + }); + it('rejects a value outside a static filter options', () => { const resolved = resolveDashboardVariables( [staticFilter()], diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index 6c41c7981..3689c46ec 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -982,9 +982,10 @@ For configType: "sql" tiles, write ClickHouse SQL with template macros: $__filter(, $) Matches the expression against the variable's selected values (e.g \` IN ('a', 'b')\`). Expands to 1=1 when nothing is selected. - $__conditionalAll(, $) Applies the condition only while the variable has a - selection, and expands to 1=1 otherwise. Use it for - operators IN cannot express, such as NOT IN or LIKE. + $__conditionalAll(, $) Applies the condition only while specific values are + selected, and expands to 1=1 when nothing or "All" is + selected. Use it for operators IN cannot express, such + as NOT IN or LIKE. The variable argument carries the leading $, exactly as a bare reference would. QUERY PARAMETERS (ClickHouse parameterized syntax): @@ -1201,9 +1202,10 @@ Query-expression filter shape: variableName The token tiles reference. Must match [a-zA-Z][a-zA-Z0-9_]* and be at most 64 characters, and must be unique across the dashboard's variable-enabled filters. Defaults to the display name with whitespace turned into underscores and remaining illegal characters dropped, so "Service Name" becomes $Service_Name and a label with nothing token-safe in it (a non-ASCII name, for instance) must set this field explicitly. Rejected when isVariableEnabled is not true. Static filter shape: - { type: "STATIC_LIST", name, options, variableName? } + { type: "STATIC_LIST", name, options, allowAll?, variableName? } options 1-1000 unique, non-empty strings the dropdown offers, in display order. + allowAll Set true to add an "All" choice to the dropdown, which selects every option. Multi-select filters only (rejected with maxSelections: 1). With "All" selected, $variableName and $__filter use every option, and $__conditionalAll expands to 1=1. No expression, sourceId, where, or appliesToSourceIds: the list is hand-authored, nothing is queried. It has no mode flags either. A static filter is always variable-only, so tiles must reference $variableName for the selection to have any effect. Pass the column explicitly in macros ($__filter(, $)); the one-argument $__filter($var) form fails because the filter has no expression of its own. @@ -1280,7 +1282,7 @@ THREE WAYS TO REFERENCE A VARIABLE The one-argument form $__filter($service) reuses the filter's own expression, but it fails when the filter does not carry one, so pass the expression explicitly whenever the tile's column differs from the filter's. $__conditionalAll(, $) - Applies the condition verbatim while something is selected, and 1=1 otherwise. Use it for anything IN cannot express. The condition itself should reference the variable. + Applies the condition verbatim while specific values are selected, and 1=1 when nothing or "All" (allowAll filters) is selected. Use it for anything IN cannot express. The condition itself should reference the variable. where: "$__conditionalAll(ServiceName NOT IN ($service), $service)" $variableName / \${variableName} / \${variableName:format} @@ -1350,6 +1352,7 @@ VALIDATING clickstack_query_tile and clickstack_query_tiles expand variables with an EMPTY selection by default, which is what a freshly-opened dashboard looks like. Optionally, pass variableValues to check that a tile narrows correctly once something is picked: variableValues: [{ name: "service", values: ["checkout"] }] For a STATIC_LIST filter's variable, every supplied value must be one of the filter's declared options; the dashboard UI can never select anything else, so other values are rejected. +For a filter with allowAll, simulate "All" with { name, values: [], all: true }. Both tools report variable problems under "warnings". Alerts on a tile always evaluate with every variable empty, so a tile carrying an alert must stay correct with nothing selected. == TABLE TILE LINKING (config.onClick) == diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index 6b224005e..f4871c85d 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -1777,6 +1777,12 @@ const mcpStaticListFilterSchema = z options: StaticListDashboardFilterSchema.shape.options.describe( 'The values the dropdown offers, in display order, without duplicates.', ), + allowAll: StaticListDashboardFilterSchema.shape.allowAll.describe( + 'Set true to add an "All" choice to the dropdown, which selects every ' + + 'option. Multi-select filters only (rejected with maxSelections: 1). ' + + 'With "All" selected, $variableName and $__filter use every option, ' + + 'and $__conditionalAll expands to 1=1.', + ), }) .describe( 'A variable-only dashboard filter whose dropdown offers a hand-authored options ' + @@ -2163,6 +2169,10 @@ const mcpVariableSavedFilterValueSchema = values: variableValueShape.values.describe( 'Selected values for the variable, e.g. ["api", "web"].', ), + all: variableValueShape.all.describe( + 'Set true to save "All" as the selection; `values` is then ignored ' + + '(pass []). Only for filters that set allowAll.', + ), }); const adhocValueShape = externalAdhocSavedFilterValueSchema.shape; diff --git a/packages/api/src/mcp/tools/dashboards/variables.ts b/packages/api/src/mcp/tools/dashboards/variables.ts index a20432df5..494052422 100644 --- a/packages/api/src/mcp/tools/dashboards/variables.ts +++ b/packages/api/src/mcp/tools/dashboards/variables.ts @@ -1,4 +1,5 @@ import { + filterSupportsAllValue, getDashboardVariableDeclarations, getDashboardVariableFilters, getFilterVariableName, @@ -19,6 +20,7 @@ import type { SourceKind, } from '@hyperdx/common-utils/dist/types'; import { isFilterSingleSelect } from '@hyperdx/common-utils/dist/variables'; +import { expandAllSelections } from '@hyperdx/common-utils/dist/variableSelection'; import { z } from 'zod/v3'; import type { McpContext } from '@/mcp/tools/types'; @@ -63,6 +65,13 @@ export const mcpVariableValuesParam = z 'For a DATA_SOURCE or CONNECTION variable, pass one source or connection ID; it ' + "overrides the dashboard's saved selection.", ), + all: z + .literal(true) + .optional() + .describe( + 'Set true to simulate "All" on a filter that sets allowAll; ' + + '`values` is then ignored (pass []).', + ), }), ) .describe( @@ -117,11 +126,30 @@ export function resolveDashboardVariables( }; } + // Only filters that opt in offer "All", so the dashboard can't produce it elsewhere + const allCapableNames = new Set( + getDashboardVariableFilters(filters) + .filter(({ filter }) => filterSupportsAllValue(filter)) + .map(({ name }) => name), + ); + const allErrors = variableValues + .filter(({ name, all }) => all && !allCapableNames.has(name)) + .map( + ({ name }) => + `Variable "${name}" belongs to a filter that does not offer "All"; ` + + 'pass specific values, or set allowAll on the filter.', + ); + if (allErrors.length > 0) { + return { error: allErrors.join('\n') }; + } + // `values` is ignored for "All", so it isn't checked below + const explicitValues = variableValues.filter(({ all }) => !all); + // A static filter's dropdown can only ever offer its declared options, so a // simulated selection outside them can never occur in the UI — reject it as // a typo rather than running a query the dashboard cannot produce. const staticOptionsByName = buildStaticOptionsByName(filters); - const optionErrors = variableValues.flatMap(({ name, values }) => { + const optionErrors = explicitValues.flatMap(({ name, values }) => { const options = staticOptionsByName.get(name); if (!options) return []; const invalid = values.filter(value => !options.includes(value)); @@ -141,7 +169,7 @@ export function resolveDashboardVariables( const singleSelectNames = new Set( variables.filter(isFilterSingleSelect).map(variable => variable.name), ); - const singleSelectErrors = variableValues + const singleSelectErrors = explicitValues .filter( ({ name, values }) => values.length > 1 && singleSelectNames.has(name), ) @@ -155,12 +183,18 @@ export function resolveDashboardVariables( } // Override the default empty selection with the given variableValues - for (const { name, values } of variableValues) { + for (const { name, values, all } of variableValues) { const variable = byName.get(name); - if (variable) variable.values = values; + if (!variable) continue; + if (all) { + variable.all = true; + variable.values = []; + } else { + variable.values = values; + } } - return { variables }; + return { variables: expandAllSelections(variables, staticOptionsByName) }; } /** The team's sources and connections that a reference variable may select. */ 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 9b4fbb1dc..0a9cec44b 100644 --- a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts +++ b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts @@ -1203,6 +1203,74 @@ describe('dashboard router', () => { }); }); + describe('"All" option', () => { + const makeStaticFilter = (overrides = {}) => ({ + id: new Types.ObjectId().toString(), + type: 'STATIC_LIST' as const, + name: 'Environment', + options: ['prod', 'staging'], + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'env', + ...overrides, + }); + const allValue = { type: 'variable', name: 'env', values: [], all: true }; + + it('persists allowAll and a saved "all" value', async () => { + const filter = makeStaticFilter({ allowAll: true }); + + const created = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + filters: [filter], + savedFilterValues: [allValue], + }) + .expect(200); + + const stored = await Dashboard.findById(created.body.id).lean(); + expect(stored?.filters).toEqual([filter]); + expect(stored?.savedFilterValues).toEqual([allValue]); + }); + + it('drops a saved "all" value for a filter without allowAll', async () => { + const created = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + filters: [makeStaticFilter()], + savedFilterValues: [allValue], + }) + .expect(200); + + const stored = await Dashboard.findById(created.body.id).lean(); + expect(stored?.savedFilterValues).toEqual([]); + }); + + it('saves a dashboard whose saved "all" value went stale', async () => { + const filter = makeStaticFilter({ allowAll: true }); + const created = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + filters: [filter], + savedFilterValues: [allValue], + }) + .expect(200); + + await agent + .patch(`/dashboards/${created.body.id}`) + .send({ + ...created.body, + filters: [{ ...filter, allowAll: false }], + }) + .expect(200); + + const stored = await Dashboard.findById(created.body.id).lean(); + expect(stored?.savedFilterValues).toEqual([]); + }); + }); + describe('required filters', () => { const makeFilter = (overrides = {}) => ({ id: new Types.ObjectId().toString(), diff --git a/packages/api/src/routers/api/dashboards.ts b/packages/api/src/routers/api/dashboards.ts index ceb5dd45d..6d65d38ab 100644 --- a/packages/api/src/routers/api/dashboards.ts +++ b/packages/api/src/routers/api/dashboards.ts @@ -1,3 +1,4 @@ +import { dropUnsupportedAllValues } from '@hyperdx/common-utils/dist/dashboardFilterValues'; import { getVariableReferenceError, validateDashboardFilterModes, @@ -190,6 +191,12 @@ router.post( // client-supplied value would otherwise persist and hand the caller's // dashboard to the provisioner. const dashboard = _.omit(req.body, 'provisioned'); + if (dashboard.savedFilterValues) { + dashboard.savedFilterValues = dropUnsupportedAllValues( + dashboard.filters ?? [], + dashboard.savedFilterValues, + ); + } const filterError = getVariableReferenceError(req.body.tiles, req.body.filters) ?? @@ -237,6 +244,15 @@ router.patch( // Nulls survive: the schema's optional fields are `.nullable()`, and a // null still signals field removal downstream. const updates = DashboardWithoutIdSchema.partial().parse(req.body); + // Dropped rather than rejected: the UI resends the stored defaults on + // every save, so a stale "all" left after allowAll is turned off would + // otherwise block every later edit. + if (updates.savedFilterValues) { + updates.savedFilterValues = dropUnsupportedAllValues( + updates.filters ?? dashboard.filters ?? [], + updates.savedFilterValues, + ); + } const filterError = // Only references this update adds are checked, so a filter edit 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 26e998805..ac770989d 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 @@ -6157,34 +6157,55 @@ describe('External API v2 Dashboards - new format', () => { }); }); - // Held back until the dashboard UI offers "All". describe('"All" option', () => { - it.each([ - ['STATIC_LIST', () => staticFilterInput({ allowAll: true })], - [ - 'SQL_QUERY', - () => ({ - id: new ObjectId().toString(), - type: 'SQL_QUERY' as const, - name: 'Environment', - connectionId: connection._id.toString(), - sqlTemplate: 'SELECT DISTINCT env FROM envs', - allowAll: true, - }), - ], - ] as const)( - 'rejects allowAll on a %s filter', - async (_type, makeFilter) => { - await expectFilters([makeFilter()], 400); - }, - ); + const allValue = { type: 'variable', name: 'env', values: [], all: true }; - it('rejects a saved "all" value', async () => { + it('accepts allowAll and a saved "all" value on a static list filter', async () => { const response = await sendFilters( - [staticFilterInput()], - [{ type: 'variable', name: 'env', values: [], all: true }], + [staticFilterInput({ allowAll: true })], + [allValue], ); + + expect(response.status).toBe(200); + expect(response.body.data.filters[0].allowAll).toBe(true); + expect(response.body.data.savedFilterValues).toEqual([allValue]); + }); + + it('rejects allowAll on a single-select filter', async () => { + const response = await sendFilters([ + staticFilterInput({ allowAll: true, maxSelections: 1 }), + ]); + expect(response.status).toBe(400); + expect(JSON.stringify(response.body)).toContain( + 'sets allowAll but is single-select', + ); + }); + + it('rejects a saved "all" value for a filter without allowAll', async () => { + const response = await sendFilters([staticFilterInput()], [allValue]); + + expect(response.status).toBe(400); + expect(JSON.stringify(response.body)).toContain( + 'sets all: true, but its filter does not offer', + ); + }); + + // Held back until SQL query filters expand "All". + it('rejects allowAll on a SQL query filter', async () => { + await expectFilters( + [ + { + id: new ObjectId().toString(), + type: 'SQL_QUERY' as const, + name: 'Environment', + connectionId: connection._id.toString(), + sqlTemplate: 'SELECT DISTINCT env FROM envs', + allowAll: true, + }, + ], + 400, + ); }); }); diff --git a/packages/api/src/routers/external-api/v2/dashboards.ts b/packages/api/src/routers/external-api/v2/dashboards.ts index e2c69a199..cfcf04053 100644 --- a/packages/api/src/routers/external-api/v2/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/dashboards.ts @@ -103,6 +103,13 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * type: string * maxLength: 10000 * example: ["hdx-oss-dev-api"] + * all: + * type: boolean + * enum: [true] + * description: > + * Set to true to select "All"; `values` is then ignored, so send + * an empty array. Only allowed for filters that set allowAll. + * example: true * AdhocSavedFilterValue: * type: object * required: [type, name, conditions] @@ -2722,6 +2729,14 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * The values this filter's dropdown offers. Must be non-empty and * free of duplicates. * example: ["prod", "staging", "dev"] + * allowAll: + * type: boolean + * description: | + * Adds an "All" choice to the dropdown, which selects every option. + * Only allowed on multi-select filters (not with maxSelections 1). + * With "All" selected, `$variableName` and `$__filter` use every + * option, and `$__conditionalAll` expands to 1=1. + * example: true * isBroadcastEnabled: * type: boolean * enum: [false] diff --git a/packages/api/src/routers/external-api/v2/utils/dashboards.ts b/packages/api/src/routers/external-api/v2/utils/dashboards.ts index 5b19b660a..e67de43f4 100644 --- a/packages/api/src/routers/external-api/v2/utils/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/utils/dashboards.ts @@ -13,6 +13,7 @@ import { validateDashboardFilterModes, validateDashboardFilterOptionUniqueness, validateDashboardFilterVariableNames, + validateDashboardSavedFilterValues, validateDashboardTileContainerRefs, } from '@hyperdx/common-utils/dist/dashboardValidation'; import { @@ -2016,6 +2017,11 @@ function buildDashboardBodySchema(filterSchema: z.ZodTypeAny): z.ZodEffects< validateDashboardFilterFieldGating(data.filters ?? [], ctx); validateDashboardFilterOptionUniqueness(data.filters ?? [], ctx); + validateDashboardSavedFilterValues( + data.filters ?? [], + data.savedFilterValues ?? [], + ctx, + ); }); } diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index 6f99aa486..c0ea28e7d 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -200,11 +200,8 @@ const externalQueryExpressionFilterShape = }); // A static filter's mode flags each accept exactly one value, so callers may -// omit them and get that value. `allowAll` is held back until the dashboard UI -// offers "All". -const externalStaticListFilterShape = StaticListDashboardFilterSchema.omit({ - allowAll: true, -}).extend({ +// omit them and get that value. +const externalStaticListFilterShape = StaticListDashboardFilterSchema.extend({ isBroadcastEnabled: z.literal(false).default(false), isVariableEnabled: z.literal(true).default(true), }); @@ -218,7 +215,7 @@ const externalPromqlLabelFilterShape = PromqlLabelDashboardFilterSchema.omit({ }); // `connectionId`/`sourceId` rather than `connection`/`source`, matching raw SQL -// tiles. `allowAll` is held back until the dashboard UI offers "All". +// tiles. `allowAll` is held back until SQL query filters expand "All". const externalSqlQueryFilterShape = SqlQueryDashboardFilterSchema.omit({ connection: true, source: true, @@ -304,9 +301,8 @@ export const externalSqlSavedFilterValueSchema = z.object({ condition: z.string().max(10000), }); -// `all` is held back until the dashboard UI offers "All". export const externalVariableSavedFilterValueSchema = - VariableFilterValueSchema.omit({ all: true }).strict(); + VariableFilterValueSchema.strict(); export const externalAdhocSavedFilterValueSchema = AdhocFilterValueSchema.strict(); diff --git a/packages/app/src/DashboardFilters.tsx b/packages/app/src/DashboardFilters.tsx index 8205f0b40..453f6d12d 100644 --- a/packages/app/src/DashboardFilters.tsx +++ b/packages/app/src/DashboardFilters.tsx @@ -1,6 +1,7 @@ import { useMemo, useState } from 'react'; import { FilterSelection } from '@hyperdx/common-utils/dist/dashboardFilterValues'; import { + filterSupportsAllValue, getFilterBroadcastTarget, getFilterVariableName, getPendingFilterValuesVariables, @@ -22,6 +23,7 @@ import { DashboardFilter, } from '@hyperdx/common-utils/dist/types'; import { isFilterSingleSelect } from '@hyperdx/common-utils/dist/variables'; +import { VariableSelection } from '@hyperdx/common-utils/dist/variableSelection'; import { Group, Stack, Text } from '@mantine/core'; import { IconRefresh } from '@tabler/icons-react'; @@ -43,8 +45,10 @@ import { useDashboardFilterValues } from './hooks/useDashboardFilterValues'; interface DashboardFilterSelectProps { filter: DashboardFilter; - onChange: (values: string[]) => void; + onChange: (selection: VariableSelection) => void; + /** Concrete selected values. Empty when "All" is selected. */ value: string[]; + isAllSelected?: boolean; values?: string[]; isLoading?: boolean; isError?: boolean; @@ -106,6 +110,7 @@ const DashboardFilterSelect = ({ filter, onChange, value, + isAllSelected = false, values, isLoading, isError, @@ -114,7 +119,8 @@ const DashboardFilterSelect = ({ }: DashboardFilterSelectProps) => { const valuesOrEmptyMemo = useMemo(() => values ?? [], [values]); const effect = getFilterEffect(filter); - const isMissingRequiredValue = isFilterRequired(filter) && value.length === 0; + const hasSelection = isAllSelected || value.length > 0; + const isMissingRequiredValue = isFilterRequired(filter) && !hasSelection; return ( @@ -144,8 +150,10 @@ const DashboardFilterSelect = ({
= new Map(); interface DashboardFilterProps { filters: DashboardFilter[]; selectionByFilterId: ReadonlyMap; - onSetFilterValue: (filterId: string, values: string[]) => void; + onSetFilterValue: (filterId: string, selection: VariableSelection) => void; adhocConditionsByFilterId?: ReadonlyMap; onSetAdhocConditions?: ( filterId: string, @@ -241,6 +249,15 @@ const DashboardFilters = ({ selectionByFilterId: linked ? selectionByFilterId : EMPTY_SELECTIONS, }); + // "All" is carried on the variable, since the regular selection can't hold it + const allSelectedVariableNames = useMemo( + () => + new Set( + variables?.filter(variable => variable.all).map(({ name }) => name), + ), + [variables], + ); + // Linking narrows queried dropdowns by sibling selections; a static // list can neither constrain nor be constrained, so it doesn't count. const linkableFiltersCount = useMemo( @@ -342,9 +359,12 @@ const DashboardFilters = ({ : filterErrorMessages?.get(filter.id) } pendingVariables={pendingVariables} - onChange={values => onSetFilterValue(filter.id, values)} + onChange={selection => onSetFilterValue(filter.id, selection)} values={queriedFilterValues?.values} value={selectedValues} + isAllSelected={allSelectedVariableNames.has( + getFilterVariableName(filter) ?? '', + )} /> ); })} diff --git a/packages/app/src/components/DashboardFiltersModal/AllOptionCheckbox.tsx b/packages/app/src/components/DashboardFiltersModal/AllOptionCheckbox.tsx new file mode 100644 index 000000000..0c732163a --- /dev/null +++ b/packages/app/src/components/DashboardFiltersModal/AllOptionCheckbox.tsx @@ -0,0 +1,29 @@ +import { useWatch } from 'react-hook-form'; + +import { CheckBoxControlled } from '@/components/InputControlled'; + +import { FilterFormControl } from './filterFormState'; + +/** + * Opts a filter into offering "All" in its dropdown. Hidden for single-select + * filters, which don't offer it. + */ +export const AllOptionCheckbox = ({ + control, +}: { + control: FilterFormControl; +}) => { + const isSingleSelect = useWatch({ control, name: 'isSingleSelect' }); + if (isSingleSelect) return null; + + return ( + + ); +}; diff --git a/packages/app/src/components/DashboardFiltersModal/StaticListFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/StaticListFilterEditForm.tsx index 9261ed304..f1465ec15 100644 --- a/packages/app/src/components/DashboardFiltersModal/StaticListFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/StaticListFilterEditForm.tsx @@ -2,6 +2,7 @@ import { Controller, useFormState } from 'react-hook-form'; import { DashboardFilter } from '@hyperdx/common-utils/dist/types'; import { TagsInput } from '@mantine/core'; +import { AllOptionCheckbox } from './AllOptionCheckbox'; import { CustomInputWrapper } from './CustomInputWrapper'; import { FilterFormControl } from './filterFormState'; import { VariableNameInput } from './VariableNameInput'; @@ -47,6 +48,8 @@ export const StaticListFilterEditForm = ({ /> + + ); diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx b/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx index d2980d940..74f583025 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx @@ -459,6 +459,40 @@ describe('DashboardFiltersModal', () => { expect(screen.getByTestId('filter-single-select-checkbox')).toBeChecked(); }); + it('saves a static filter offering "All" 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-allow-all-checkbox')); + await user.click(screen.getByTestId('save-filter-button')); + + await waitFor(() => expect(onSaveFilter).toHaveBeenCalledTimes(1)); + const saved: StaticListDashboardFilter = onSaveFilter.mock.calls[0][0]; + expect(saved.allowAll).toBe(true); + + renderModal({ filters: [saved] }); + await user.click( + screen.getAllByTestId(`edit-filter-button-${saved.name}`)[0], + ); + + expect(screen.getByTestId('filter-allow-all-checkbox')).toBeChecked(); + }); + + it('hides the "All" option for a single-select filter', async () => { + const { user } = renderModal(); + + await user.click(screen.getByTestId('add-filter-button')); + await selectFilterType(user, 'Static values'); + expect(screen.getByTestId('filter-allow-all-checkbox')).toBeInTheDocument(); + + await user.click(screen.getByTestId('filter-single-select-checkbox')); + + expect(screen.queryByTestId('filter-allow-all-checkbox')).toBeNull(); + }); + 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 4eb861896..1bb87119d 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts @@ -638,3 +638,48 @@ describe('maxSelections', () => { expect(saved).toMatchObject({ minSelections: 1, maxSelections: 1 }); }); }); + +describe('allowAll', () => { + it('round-trips allowAll on a static list filter', () => { + const saved = toSavedFilter( + formValues({ ...byType.STATIC_LIST, allowAll: true }), + ); + + expect(saved).toMatchObject({ allowAll: true }); + expect(toFormValues(saved).allowAll).toBe(true); + }); + + it('stores nothing for allowAll on a single-select static list filter', () => { + const saved = toSavedFilter( + formValues({ + ...byType.STATIC_LIST, + allowAll: true, + isSingleSelect: true, + }), + ); + + expect(saved).toMatchObject({ allowAll: undefined }); + }); + + it('stores nothing for allowAll when it is off', () => { + const saved = toSavedFilter( + formValues({ ...byType.STATIC_LIST, allowAll: false }), + ); + + expect(saved).toMatchObject({ allowAll: undefined }); + }); + + // SQL query filters don't expand "All" yet + it('stores nothing for allowAll after switching a static list to a SQL query', () => { + const saved = toSavedFilter( + formValues({ + ...byType.STATIC_LIST, + allowAll: true, + ...byType.SQL_QUERY, + }), + ); + + expect(saved.type).toBe('SQL_QUERY'); + expect(saved).not.toHaveProperty('allowAll'); + }); +}); diff --git a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts index 804df515c..c6d5cef4f 100644 --- a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts +++ b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts @@ -104,6 +104,7 @@ export const toFormValues = ( // STATIC_LIST fields options: staticList?.options ?? [], + allowAll: staticList?.allowAll ?? false, // PROMETHEUS_LABEL fields label: promqlLabel?.label ?? '', @@ -127,7 +128,8 @@ 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 no key is stored unless it's relevant - const { isRequired, isGlobalRequirement, isSingleSelect, ...rest } = values; + const { isRequired, isGlobalRequirement, isSingleSelect, allowAll, ...rest } = + values; const selectionLimits = { ...(isRequired ? { @@ -142,6 +144,8 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { return DashboardFilterSchema.parse({ ...rest, options: values.options.map(option => option.trim()), + // Single-select filters don't offer "All", and false isn't stored + allowAll: allowAll && !isSingleSelect ? true : undefined, isBroadcastEnabled: false, isVariableEnabled: true, variableName: getFilterVariableName(values), @@ -166,6 +170,8 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { ...rest, source: values.source || undefined, sqlTemplate: values.sqlTemplate.trim(), + // No allowAll until SQL query filters expand "All": a static list's + // checkbox value survives switching the type. isBroadcastEnabled: false, isVariableEnabled: true, variableName: getFilterVariableName(values), diff --git a/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.stories.tsx b/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.stories.tsx index d0cebf3ad..f0eefe151 100644 --- a/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.stories.tsx +++ b/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.stories.tsx @@ -1,5 +1,9 @@ import { useState } from 'react'; import { sample, times } from 'lodash'; +import { + isAllSelection, + VariableSelection, +} from '@hyperdx/common-utils/dist/variableSelection'; import { Box } from '@mantine/core'; import { Meta, StoryObj } from '@storybook/nextjs'; @@ -31,15 +35,25 @@ const meta: Meta = { argTypes: { data: { table: { disable: true } }, values: { table: { disable: true } }, + isAllOptionSelected: { table: { disable: true } }, onChange: { table: { disable: true } }, }, decorators: [ (Story, ctx) => { - const [values, setValues] = useState([]); + const [selection, setSelection] = useState([]); + const isAllOptionSelected = isAllSelection(selection); return ( - + ); }, @@ -50,3 +64,5 @@ export default meta; type Story = StoryObj; export const Primary: Story = {}; + +export const WithAllOption: Story = { args: { enableAllOption: true } }; diff --git a/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.tsx b/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.tsx index ad5ae3d4d..389053d04 100644 --- a/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.tsx +++ b/packages/app/src/components/VirtualMultiSelect/VirtualMultiSelect.tsx @@ -5,6 +5,7 @@ import { useRef, useState, } from 'react'; +import type { VariableSelection } from '@hyperdx/common-utils/dist/variableSelection'; import { CheckIcon, CloseButton, @@ -18,6 +19,12 @@ import { } from '@mantine/core'; import { useVirtualizer } from '@tanstack/react-virtual'; +// UI-internal routing token for the "All" combobox row. Never stored or emitted. +const ALL_ROW_VALUE = '__hdx_all_row__'; + +// UI-visible label for the "All" combobox row. +const ALL_ROW_LABEL = 'All'; + type VirtualMultiSelectProps = { data: string[]; disabled?: boolean; @@ -27,8 +34,14 @@ type VirtualMultiSelectProps = { /** Whether to sort options before rendering. True by default */ sort?: boolean; isMultiSelect?: boolean; + /** Concrete selected values. Empty when "all" is selected. */ values: string[]; - onChange: (values: string[]) => void; + /** Whether to show the "All" option. */ + enableAllOption?: boolean; + /** Whether the "All" option is currently selected. */ + isAllOptionSelected?: boolean; + /** Emits an explicit list of values, or `{ all: true }` for "All". */ + onChange: (next: VariableSelection) => void; 'data-testid'?: string; }; @@ -42,11 +55,19 @@ export function VirtualMultiSelect({ values, onChange, 'data-testid': dataTestId, + enableAllOption = false, + isAllOptionSelected: allSelected, }: VirtualMultiSelectProps) { const viewportRef = useRef(null); const [search, setSearch] = useState(''); + const isAllSelected = enableAllOption && !!allSelected; + const concreteValues = isAllSelected ? [] : values; + const showAllOption = + enableAllOption && + ALL_ROW_LABEL.toLowerCase().includes(search.trim().toLowerCase()); + const sorted = useMemo(() => { return sort ? data.toSorted((a, b) => a.localeCompare(b)) : data; }, [data, sort]); @@ -80,26 +101,44 @@ export function VirtualMultiSelect({ const handleRemoveAllValues = () => onChange([]); const handleAddValue = (val: string) => { + if (isAllSelected) { + onChange([val]); + return; + } if (!values.includes(val)) { onChange(isMultiSelect ? [...values, val] : [val]); } }; const handleSelectValue = (val: string) => { - if (values.includes(val)) { + if (enableAllOption && val === ALL_ROW_VALUE) { + // Toggle the "All" row: selecting it emits the structural marker and + // clears any concrete selection; selecting it again clears everything. + onChange(isAllSelected ? [] : { all: true }); + } else if (!isAllSelected && values.includes(val)) { handleRemoveValue(val); } else { + // Picking a concrete value while "All" is active narrows to that value. handleAddValue(val); } + // Clear the search input after a value is selected, matching the behavior + // of a non-virtualized Mantine MultiSelect with search. setSearch(''); if (!isMultiSelect) combobox.closeDropdown(); }; const handleKeyDown: KeyboardEventHandler = event => { - if (event.key === 'Backspace' && search.length === 0 && values.length > 0) { - event.preventDefault(); - handleRemoveValue(values[values.length - 1]); - return; + if (event.key === 'Backspace' && search.length === 0) { + if (isAllSelected) { + event.preventDefault(); + onChange([]); + return; + } + if (values.length > 0) { + event.preventDefault(); + handleRemoveValue(values[values.length - 1]); + return; + } } if (event.key === 'Enter') { @@ -140,7 +179,7 @@ export function VirtualMultiSelect({ disabled={disabled} size="xs" data-testid={dataTestId} - {...(values.length + {...(isAllSelected || values.length ? { rightSection: ( - {values.map(item => ( + {(isAllSelected + ? [ + { + key: ALL_ROW_VALUE, + label: ALL_ROW_LABEL, + onRemove: () => onChange([]), + }, + ] + : concreteValues.map(item => ({ + key: item, + label: item, + onRemove: () => handleRemoveValue(item), + })) + ).map(({ key, label, onRemove }) => ( handleRemoveValue(item)} + onRemove={onRemove} // manually disabling instead of using `disabled` prop // `disabled` prop hides remove button which can cause layout to jump aria-disabled={disabled} styles={{ root: { pointerEvents: disabled ? 'none' : 'auto' } }} > - {item} + {label} ))} @@ -182,6 +234,9 @@ export function VirtualMultiSelect({ placeholder={placeholder} onChange={handleChange} onKeyDown={handleKeyDown} + data-has-values={ + isAllSelected || values.length > 0 ? 'true' : 'false' + } /> @@ -190,6 +245,16 @@ export function VirtualMultiSelect({ + {showAllOption && ( + + + {isAllSelected && } + + {ALL_ROW_LABEL} + + + + )} {options.length > 0 ? ( {virtualItems.map(virtualItem => { const item = options[virtualItem.index]; + const isSelected = concreteValues.includes(item); return (
- + - {values.includes(item) && } + {isSelected && } {item} @@ -234,9 +297,13 @@ export function VirtualMultiSelect({
) : ( - - {loading ? 'Loading…' : 'Nothing found...'} - + // The "All" row is rendered above the (empty) list, so only fall + // back to the empty/loading hint when there is nothing at all. + !showAllOption && ( + + {loading ? 'Loading…' : 'Nothing found...'} + + ) )}
diff --git a/packages/app/src/components/VirtualMultiSelect/__tests__/VirtualMultiSelect.test.tsx b/packages/app/src/components/VirtualMultiSelect/__tests__/VirtualMultiSelect.test.tsx new file mode 100644 index 000000000..8fd0c7cbf --- /dev/null +++ b/packages/app/src/components/VirtualMultiSelect/__tests__/VirtualMultiSelect.test.tsx @@ -0,0 +1,57 @@ +import { screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { VirtualMultiSelect } from '../VirtualMultiSelect'; + +// Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks it. +window.HTMLElement.prototype.scrollIntoView = jest.fn(); + +const renderSelect = ( + props: Partial> = {}, +) => { + const onChange = jest.fn(); + renderWithMantine( + , + ); + return { onChange, user: userEvent.setup() }; +}; + +describe('VirtualMultiSelect "All" option', () => { + it('is not offered unless enabled', async () => { + const { user } = renderSelect(); + + await user.click(screen.getByRole('textbox')); + + expect(screen.queryByText('All')).toBeNull(); + }); + + it('selects "All" from the dropdown', async () => { + const { onChange, user } = renderSelect({ enableAllOption: true }); + + await user.click(screen.getByRole('textbox')); + await user.click(await screen.findByText('All')); + + expect(onChange).toHaveBeenCalledWith({ all: true }); + }); + + it('shows "All" as a pill that clears the selection when removed', async () => { + const { onChange, user } = renderSelect({ + enableAllOption: true, + isAllOptionSelected: true, + }); + + const pill = within(screen.getByTestId('select')) + .getByText('All') + .closest('.mantine-Pill-root'); + if (!pill) throw new Error('expected an "All" pill'); + await user.click(within(pill).getByRole('button', { hidden: true })); + + expect(onChange).toHaveBeenCalledWith([]); + }); +}); diff --git a/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx b/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx index a2c7f2038..bc5170db9 100644 --- a/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx +++ b/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx @@ -7,6 +7,7 @@ import { DashboardFilterValue, QueryExpressionDashboardFilter, SourceKind, + StaticListDashboardFilter, } from '@hyperdx/common-utils/dist/types'; import { act, renderHook } from '@testing-library/react'; @@ -992,6 +993,90 @@ describe('useDashboardFilters', () => { }); }); + describe('"All" selection', () => { + const envFilter: StaticListDashboardFilter = { + id: 'env', + type: 'STATIC_LIST', + name: 'Environment', + options: ['staging', 'prod'], + allowAll: true, + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'env', + }; + const allEntry: DashboardFilterValue = { + type: 'variable', + name: 'env', + values: [], + all: true, + }; + + it('stores "All" as an all entry', () => { + const { result } = renderHook(() => useDashboardFilters([envFilter])); + + act(() => { + result.current.setFilterValue('env', { all: true }); + }); + + expect(mockState).toEqual([allEntry]); + }); + + it('keeps "All" when a sibling filter changes', () => { + mockState = [allEntry]; + const filters = [envFilter, mockFilters[1]]; + const { result } = renderHook(() => useDashboardFilters(filters)); + + act(() => { + result.current.setFilterValue('filter2', ['api']); + }); + + expect(mockState).toEqual([ + { type: 'sql', condition: "service.name IN ('api')" }, + allEntry, + ]); + }); + + it('drops "All" for a filter that does not offer it', () => { + mockState = [allEntry]; + const filters = [{ ...envFilter, allowAll: false }, mockFilters[1]]; + const { result } = renderHook(() => useDashboardFilters(filters)); + + act(() => { + result.current.setFilterValue('filter2', ['api']); + }); + + expect(mockState).toEqual([ + { type: 'sql', condition: "service.name IN ('api')" }, + ]); + }); + + it('expands a static list to every option on the variable', () => { + mockState = [allEntry]; + + const { result } = renderHook(() => useDashboardFilters([envFilter])); + + expect(result.current.variables).toEqual([ + { + name: 'env', + expression: undefined, + values: ['prod', 'staging'], + maxSelections: undefined, + all: true, + }, + ]); + }); + + it('satisfies a required filter', () => { + mockState = [allEntry]; + + const { result } = renderHook(() => + useDashboardFilters([{ ...envFilter, minSelections: 1 }]), + ); + + expect(result.current.unsatisfiedRequiredFilters).toEqual([]); + }); + }); + describe('ad hoc filters', () => { const adhocFilter: AdhocDashboardFilter = { id: 'adhoc1', diff --git a/packages/app/src/hooks/useDashboardFilters.tsx b/packages/app/src/hooks/useDashboardFilters.tsx index 3c54bf3d8..19bf8a6dd 100644 --- a/packages/app/src/hooks/useDashboardFilters.tsx +++ b/packages/app/src/hooks/useDashboardFilters.tsx @@ -8,6 +8,7 @@ import { parseDashboardFilterValues, ParsedDashboardFilterValues, resolveFilterSelection, + resolveVariableSelection, serializeDashboardFilterValues, VariableEntryValue, } from '@hyperdx/common-utils/dist/dashboardFilterValues'; @@ -19,6 +20,7 @@ import { doesFilterApplyToSource, FilterState, filtersToQuery, + filterSupportsAllValue, getDashboardVariableFilters, getFilterExpression, getFilterVariableName, @@ -26,6 +28,7 @@ import { isAdhocFilter, isFilterBroadcastEnabled, isQueryExpressionFilter, + isStaticListFilter, mergeAdhocConditions, } from '@hyperdx/common-utils/dist/filters'; import { @@ -49,6 +52,12 @@ import { DashboardFilter, TSource, } from '@hyperdx/common-utils/dist/types'; +import { + expandAllSelections, + isAllSelection, + selectionHasValue, + VariableSelection, +} from '@hyperdx/common-utils/dist/variableSelection'; import { notifyAdhocConditionTooLong, @@ -70,6 +79,13 @@ const hasSelection = (selection: FilterSelection): boolean => const isRepresentableAsVariable = (selection: FilterSelection): boolean => selection.excluded.size === 0 && selection.range == null; +const toVariableEntryValue = ( + selection: VariableSelection, +): VariableEntryValue => + isAllSelection(selection) + ? { type: 'variable', values: [], all: true } + : { type: 'variable', values: selection }; + /** Conditions are identified by content (e.g. pill keys), so drop repeats. */ const uniqConditions = (conditions: AdhocFilterCondition[]) => uniqBy(conditions, condition => JSON.stringify(condition)); @@ -98,6 +114,15 @@ const rebuildEntries = ( declaredVariableNames.add(key.name); if (byVariable.has(key.name)) continue; // First definition of a name wins. + // Read separately because the regular selection can't represent "all" + if (filterSupportsAllValue(filter)) { + const selection = resolveVariableSelection(filter, parsed); + if (selectionHasValue(selection)) { + byVariable.set(key.name, toVariableEntryValue(selection)); + } + continue; + } + const selection = resolveFilterSelection(filter, parsed); if (!selection) continue; if (!isRepresentableAsVariable(selection) && expression) { @@ -168,7 +193,7 @@ const useDashboardFilters = ( ); const setFilterValue = useCallback( - (filterId: string, values: string[]) => { + (filterId: string, values: VariableSelection) => { setFilterValueEntries(prev => { const target = filters.find(f => f.id === filterId); if (!target) return prev; @@ -181,8 +206,8 @@ const useDashboardFilters = ( const key = filterSelectionKey(target); if (key.kind === 'variable') { // Set even when empty to avoid falling back to a legacy expression-keyed value - parsed.byVariable.set(key.name, { type: 'variable', values }); - } else if (values.length === 0) { + parsed.byVariable.set(key.name, toVariableEntryValue(values)); + } else if (isAllSelection(values) || values.length === 0) { delete parsed.byExpression[key.expression]; } else { parsed.byExpression[key.expression] = { @@ -228,6 +253,7 @@ const useDashboardFilters = ( const { selectionByFilterId, + variableSelectionByFilterId, adhocConditionsByFilterId, ignoredExpressions, ignoredVariableNames, @@ -235,6 +261,7 @@ const useDashboardFilters = ( referenceVariableValues, } = useMemo<{ selectionByFilterId: ReadonlyMap; + variableSelectionByFilterId: ReadonlyMap; adhocConditionsByFilterId: ReadonlyMap; ignoredExpressions: string[]; ignoredVariableNames: string[]; @@ -247,9 +274,15 @@ const useDashboardFilters = ( // Keyed by filter ID: two definitions may share one expression const selectionByFilterId = new Map(); + // Filters that can hold "all", in a shape that can represent it + const variableSelectionByFilterId = new Map(); for (const filter of nonAdhocFilters) { const selection = resolveFilterSelection(filter, parsed); if (selection) selectionByFilterId.set(filter.id, selection); + const variableSelection = resolveVariableSelection(filter, parsed); + if (variableSelection) { + variableSelectionByFilterId.set(filter.id, variableSelection); + } } // Connections first: a data source variable may be limited to the one a @@ -333,9 +366,12 @@ const useDashboardFilters = ( name => !declaredVariableNames.has(name), ); - const variables: ChartVariable[] = variableFilters.map( + const declaredVariables: ChartVariable[] = variableFilters.map( ({ filter, name }) => { const selection = selectionByFilterId.get(filter.id); + const isAll = isAllSelection( + variableSelectionByFilterId.get(filter.id), + ); return { name, expression: getFilterExpression(filter), @@ -346,9 +382,19 @@ const useDashboardFilters = ( : [], maxSelections: 'maxSelections' in filter ? filter.maxSelections : undefined, + ...(isAll ? { all: true } : {}), }; }, ); + // A static list's options are on its definition, so "all" expands here + const variables = expandAllSelections( + declaredVariables, + new Map( + variableFilters.flatMap(({ filter, name }) => + isStaticListFilter(filter) ? [[name, filter.options]] : [], + ), + ), + ); const referenceVariableValues = new Map( referenceVariableFilters.map(({ filter, name }) => [ @@ -359,6 +405,7 @@ const useDashboardFilters = ( return { selectionByFilterId, + variableSelectionByFilterId, adhocConditionsByFilterId, variables, referenceVariableValues, @@ -400,9 +447,16 @@ const useDashboardFilters = ( unsatisfiedRequiredFilters: getUnsatisfiedRequiredFilters( resolvedFilters, selectionByFilterId, + variableSelectionByFilterId, ), }; - }, [filters, referenceVariableValues, sources, selectionByFilterId]); + }, [ + filters, + referenceVariableValues, + sources, + selectionByFilterId, + variableSelectionByFilterId, + ]); /** Returns the set of rendered filter conditions corresponding to filters matching the given predicate */ const getFiltersQueriesFor = useCallback( diff --git a/packages/app/tests/e2e/features/dashboard-all-option-filters.spec.ts b/packages/app/tests/e2e/features/dashboard-all-option-filters.spec.ts new file mode 100644 index 000000000..e0af5a45a --- /dev/null +++ b/packages/app/tests/e2e/features/dashboard-all-option-filters.spec.ts @@ -0,0 +1,70 @@ +/** + * A static list filter with "Include "All" option" offers "All" in its + * dropdown. Picking it stores `all: true` in the `filters=` param and hands + * tiles every option. + */ +import { DashboardPage } from '../page-objects/DashboardPage'; +import { expect, test } from '../utils/base-test'; +import { expectFiltersParam } from '../utils/filters-param'; + +const ENVIRONMENTS = ['prod', 'staging', 'dev']; +const ALL_ENTRY = { + type: 'variable' as const, + name: 'env', + values: [], + all: true as const, +}; + +test.describe( + 'Dashboard filter "All" option', + { tag: ['@dashboard', '@full-stack'] }, + () => { + let dashboardPage: DashboardPage; + + test.beforeEach(async ({ page }) => { + dashboardPage = new DashboardPage(page); + await dashboardPage.goto(); + await dashboardPage.createNewDashboard(); + await dashboardPage.addMarkdownTile('Envs', 'Environments: $env'); + await dashboardPage.openEditFiltersModal(); + await dashboardPage.addStaticListFilterToDashboard( + 'Environment', + ENVIRONMENTS, + { variableName: 'env', allowAll: true }, + ); + await dashboardPage.closeFiltersModal(); + }); + + test('selects every option for tiles', async ({ page }) => { + await dashboardPage.openFilterDropdown('Environment'); + await dashboardPage.getFilterOption('All').click(); + + await expect( + dashboardPage.getFilterPill('Environment', 'All'), + ).toBeVisible(); + await expectFiltersParam(page, [ALL_ENTRY]); + await expect(dashboardPage.getTile(0)).toContainText( + 'Environments: dev, prod, staging', + ); + }); + + test('replaces "All" with a value picked after it', async ({ page }) => { + await dashboardPage.openFilterDropdown('Environment'); + await dashboardPage.getFilterOption('All').click(); + await expectFiltersParam(page, [ALL_ENTRY]); + + await dashboardPage.openFilterDropdown('Environment'); + await dashboardPage.getFilterOption('prod').click(); + + await expect( + dashboardPage.getFilterPill('Environment', 'prod'), + ).toBeVisible(); + await expect( + dashboardPage.getFilterPill('Environment', 'All'), + ).toHaveCount(0); + await expectFiltersParam(page, [ + { type: 'variable', name: 'env', values: ['prod'] }, + ]); + }); + }, +); diff --git a/packages/app/tests/e2e/page-objects/DashboardPage.ts b/packages/app/tests/e2e/page-objects/DashboardPage.ts index 54a87a038..074977458 100644 --- a/packages/app/tests/e2e/page-objects/DashboardPage.ts +++ b/packages/app/tests/e2e/page-objects/DashboardPage.ts @@ -108,6 +108,7 @@ export class DashboardPage { readonly requiredFilterCheckbox: Locator; readonly globalRequirementCheckbox: Locator; readonly singleSelectCheckbox: Locator; + readonly allowAllCheckbox: Locator; readonly variableNameInput: Locator; private readonly saveButton: Locator; private readonly tileSourceSelector: Locator; @@ -177,6 +178,7 @@ export class DashboardPage { this.singleSelectCheckbox = page.getByTestId( 'filter-single-select-checkbox', ); + this.allowAllCheckbox = page.getByTestId('filter-allow-all-checkbox'); this.variableNameInput = page.getByTestId('filter-variable-name-input'); this.saveButton = page.getByTestId('chart-save-button'); @@ -1472,6 +1474,7 @@ export class DashboardPage { variableOptions?: { variableName?: string; singleSelect?: boolean; + allowAll?: boolean; } & FilterRequirementOptions, ) { await this.addFiltersButton.click(); @@ -1486,6 +1489,9 @@ export class DashboardPage { if (variableOptions?.singleSelect !== undefined) { await this.singleSelectCheckbox.setChecked(variableOptions.singleSelect); } + if (variableOptions?.allowAll !== undefined) { + await this.allowAllCheckbox.setChecked(variableOptions.allowAll); + } 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 6aa8e91e0..7a3b3e191 100644 --- a/packages/app/tests/e2e/utils/filters-param.ts +++ b/packages/app/tests/e2e/utils/filters-param.ts @@ -8,7 +8,7 @@ import { expect, type Page } from '@playwright/test'; export type FilterEntry = | { type: 'sql'; condition: string } - | { type: 'variable'; name: string; values: string[] } + | { type: 'variable'; name: string; values: string[]; all?: true } | { type: 'adhoc'; name: string; diff --git a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts index a1fd57b59..1b818b87a 100644 --- a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts +++ b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts @@ -1,5 +1,6 @@ import { configConsumesBroadcastFilters, + dropUnsupportedAllValues, filterSelectionKey, getAdhocFilterTargetsForTile, getBlockingRequiredFilterNames, @@ -7,6 +8,7 @@ import { getUnsatisfiedRequiredFilters, parseDashboardFilterValues, resolveFilterSelection, + resolveVariableSelection, serializeDashboardFilterValues, VariableEntryValue, } from '@/dashboardFilterValues'; @@ -675,6 +677,91 @@ describe('dashboardFilterValues', () => { getUnsatisfiedRequiredFilters(filters, new Map()).map(f => f.name), ).toEqual(['A', 'C']); }); + + it('omits a required filter with "All" selected', () => { + expect( + getUnsatisfiedRequiredFilters( + [required()], + new Map([['f1', included()]]), + new Map([['f1', { all: true }]]), + ), + ).toEqual([]); + }); + }); + + describe('resolveVariableSelection', () => { + const allCapable = staticFilter({ allowAll: true }); + const parse = (...entries: DashboardFilterValue[]) => + parseDashboardFilterValues(entries); + + it('reads "All" and explicit values for a filter that offers "All"', () => { + expect( + resolveVariableSelection( + allCapable, + parse({ type: 'variable', name: 'env', values: [], all: true }), + ), + ).toEqual({ all: true }); + expect( + resolveVariableSelection( + allCapable, + parse({ type: 'variable', name: 'env', values: ['prod'] }), + ), + ).toEqual(['prod']); + }); + + it('is undefined for a filter that does not offer "All"', () => { + expect( + resolveVariableSelection( + staticFilter(), + parse({ type: 'variable', name: 'env', values: [], all: true }), + ), + ).toBeUndefined(); + }); + + it('is undefined when nothing is stored for the filter', () => { + expect(resolveVariableSelection(allCapable, parse())).toBeUndefined(); + }); + }); + + describe('dropUnsupportedAllValues', () => { + const all = (name: string): DashboardFilterValue => ({ + type: 'variable', + name, + values: [], + all: true, + }); + + it('drops "all" for a filter without allowAll or made single-select', () => { + const filters = [ + staticFilter({ id: 'a', variableName: 'a' }), + staticFilter({ + id: 'b', + variableName: 'b', + allowAll: true, + maxSelections: 1, + }), + ]; + expect(dropUnsupportedAllValues(filters, [all('a'), all('b')])).toEqual( + [], + ); + }); + + it('keeps "all" on a filter that offers it, explicit values, and undeclared names', () => { + const prod: DashboardFilterValue = { + type: 'variable', + name: 'tier', + values: ['prod'], + }; + expect( + dropUnsupportedAllValues( + [ + staticFilter({ allowAll: true }), + staticFilter({ id: 'f2', variableName: 'tier' }), + ], + [all('env'), prod, all('removed')], + ), + ).toEqual([all('env'), prod, all('removed')]); + }); }); describe('getBlockingRequiredFilters', () => { diff --git a/packages/common-utils/src/dashboardFilterValues.ts b/packages/common-utils/src/dashboardFilterValues.ts index 156c1c73f..45176b456 100644 --- a/packages/common-utils/src/dashboardFilterValues.ts +++ b/packages/common-utils/src/dashboardFilterValues.ts @@ -2,6 +2,7 @@ import { doesFilterApplyToSource, FilterState, filtersToQuery, + filterSupportsAllValue, getDashboardVariableFilters, getFilterExpression, getFilterVariableName, @@ -26,6 +27,11 @@ import { VariableFilterValue, } from '@/types'; import { isFilterSingleSelect } from '@/variables'; +import { + ALL_SELECTION, + selectionHasValue, + VariableSelection, +} from '@/variableSelection'; /** * A dashboards filter/variable state is persisted as an array of entries in one of two @@ -205,16 +211,65 @@ function resolveUncappedFilterSelection( return new Map(Object.entries(parsed.byExpression)).get(expression); } +/** + * The selection of a filter that can hold "all" (`filterSupportsAllValue`), or + * undefined for any other filter or when nothing is stored for it. Use this + * rather than `resolveFilterSelection` for such filters, since that can't + * represent "all". + */ +export function resolveVariableSelection( + filter: DashboardFilter, + parsed: { byVariable: ReadonlyMap }, +): VariableSelection | undefined { + if (!filterSupportsAllValue(filter)) return undefined; + const name = getFilterVariableName(filter); + const entry = name ? parsed.byVariable.get(name) : undefined; + if (entry?.type !== 'variable') return undefined; + return entry.all ? ALL_SELECTION : entry.values; +} + +/** + * Drops `all: true` saved values whose filter no longer offers "All", e.g. after + * `allowAll` is turned off or the filter is made single-select. The dashboard + * ignores such values when it loads, so a stale one shouldn't block saving it. + * Values for undeclared names are kept, as `validateDashboardSavedFilterValues` + * keeps them. + */ +export function dropUnsupportedAllValues( + filters: DashboardFilter[], + savedFilterValues: T[], +): T[] { + const declaredNames = new Set(); + const allCapableNames = new Set(); + for (const filter of filters) { + const name = getFilterVariableName(filter); + if (!name) continue; + declaredNames.add(name); + if (filterSupportsAllValue(filter)) allCapableNames.add(name); + } + + return savedFilterValues.filter( + value => + value.type !== 'variable' || + !value.all || + !declaredNames.has(value.name) || + allCapableNames.has(value.name), + ); +} + /** The required filters that have nothing selected, in filter order. */ export function getUnsatisfiedRequiredFilters< T extends { id: string; minSelections?: number }, >( filters: T[] | undefined, selectionByFilterId: ReadonlyMap, + /** Selections of filters that can hold "all", which counts as selected. */ + variableSelectionByFilterId?: ReadonlyMap, ): T[] { return (filters ?? []).filter( filter => isFilterRequired(filter) && + !selectionHasValue(variableSelectionByFilterId?.get(filter.id)) && (selectionByFilterId.get(filter.id)?.included.size ?? 0) === 0, ); } diff --git a/packages/common-utils/src/macros.ts b/packages/common-utils/src/macros.ts index 5c98c342e..73eb68927 100644 --- a/packages/common-utils/src/macros.ts +++ b/packages/common-utils/src/macros.ts @@ -260,7 +260,7 @@ export const VARIABLE_MACRO_SUGGESTIONS: MacroSuggestion[] = [ minArgs: 2, maxArgs: 2, description: - '$__conditionalAll(, $) — applies the condition only while the variable has a selection, and expands to 1=1 otherwise. Use it for operators IN cannot express, such as NOT IN or LIKE.', + '$__conditionalAll(, $) — applies the condition only while specific values are selected, and expands to 1=1 when nothing or "All" is selected. Use it for operators IN cannot express, such as NOT IN or LIKE.', }, ];