Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tracing): tri-state facet checkboxes on filter-group facets (#73575)

Jon McCallum131f7f37b5d5
diff --git a/products/tracing/backend/tests/test_attribute_breakdown.py b/products/tracing/backend/tests/test_attribute_breakdown.py
index 10229633c26f..7d7b10ccdb9c 100644
--- a/products/tracing/backend/tests/test_attribute_breakdown.py
+++ b/products/tracing/backend/tests/test_attribute_breakdown.py
@@ -147,10 +147,44 @@ class TestTraceSpansAttributeBreakdown(_TraceSpansTestBase):
)
self.assertEqual(response.status_code, 400, response.content)
+ def test_filter_group_exclusion_scopes_the_span_list(self):
+ # The spans-list WHERE is built separately from the aggregation WHERE — an is_not status
+ # filter must scope the trace list too, not just facet counts. Fixture reused from this
+ # file because it is the only spans fixture with mixed status codes.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tracing/spans/query/",
+ {
+ "query": {
+ "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO},
+ "flatSpans": True,
+ "limit": 100,
+ "filterGroup": [{"key": "status_code", "operator": "is_not", "type": "span", "value": "Error"}],
+ }
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(len(response.json()["results"]), 6)
+
+ def test_filter_group_exclusion_scopes_the_breakdown(self):
+ # The rail's is_not exclusions must remove matching spans from other facets' counts, with
+ # label values normalising through the same path as exact ("Error" → 2). The span with no
+ # server.address at all survives (exclude-by-value, not require-the-attribute).
+ rows = self._breakdown(
+ breakdownKey="server.address",
+ breakdownType="span_attribute",
+ filterGroup=[{"key": "status_code", "operator": "is_not", "type": "span", "value": "Error"}],
+ )
+ self.assertEqual(
+ {(row["value"], row["count"]) for row in rows},
+ {("api2.amplitude.com", 2), ("api.mixpanel.com", 3), ("", 1)},
+ )
+
@parameterized.expand(
[
- # Each case selects one value of the facet's own dimension; with exclusion the facet
- # must still list every value (not collapse to the selected one).
+ # Each case selects (or excludes) one value of the facet's own dimension; with exclusion
+ # the facet must still list every value (not collapse or zero out the targeted one) —
+ # the strip is by key, both polarities.
(
"service_names_filter",
{"breakdownKey": "service_name", "breakdownType": "span", "serviceNames": ["other"]},
@@ -197,6 +231,31 @@ class TestTraceSpansAttributeBreakdown(_TraceSpansTestBase):
},
{"pod-a", "pod-b", "pod-c"},
),
+ (
+ "span_column_exclusion",
+ {
+ "breakdownKey": "status_code",
+ "breakdownType": "span",
+ "filterGroup": [{"key": "status_code", "operator": "is_not", "type": "span", "value": "Error"}],
+ },
+ {"0", "2"},
+ ),
+ (
+ "resource_attribute_exclusion",
+ {
+ "breakdownKey": "k8s.pod.name",
+ "breakdownType": "span_resource_attribute",
+ "filterGroup": [
+ {
+ "key": "k8s.pod.name",
+ "operator": "is_not",
+ "type": "span_resource_attribute",
+ "value": "pod-a",
+ }
+ ],
+ },
+ {"pod-a", "pod-b", "pod-c"},
+ ),
]
)
def test_exclude_breakdown_filter_keeps_facet_complete(self, _name, query_fields, expected_values):
diff --git a/products/tracing/frontend/components/FacetRail/Facet.tsx b/products/tracing/frontend/components/FacetRail/Facet.tsx
index eb33bb2fe76b..54d1d540636b 100644
--- a/products/tracing/frontend/components/FacetRail/Facet.tsx
+++ b/products/tracing/frontend/components/FacetRail/Facet.tsx
@@ -1,7 +1,7 @@
import { CSSProperties, useMemo } from 'react'
import { List } from 'react-window'
-import { IconChevronDown, IconChevronRight } from '@posthog/icons'
+import { IconChevronDown, IconChevronRight, IconMinusSmall } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonInput } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
@@ -15,6 +15,8 @@ interface FacetProps {
title: string
options: FacetOption[]
selected: string[]
+ /** Values in the excluded state — matching spans are filtered out. Disjoint from `selected`. */
+ excluded?: string[]
onToggle: (value: string) => void
loading?: boolean
emptyLabel?: string
@@ -49,6 +51,7 @@ export function Facet({
title,
options,
selected,
+ excluded = [],
onToggle,
loading = false,
emptyLabel = 'No values',
@@ -64,8 +67,8 @@ export function Facet({
const slug = slugify(title)
const rowProps = useMemo<FacetValueRowProps>(
- () => ({ options, selected, slug, onToggle, dimZeroCounts }),
- [options, selected, slug, onToggle, dimZeroCounts]
+ () => ({ options, selected, excluded, slug, onToggle, dimZeroCounts }),
+ [options, selected, excluded, slug, onToggle, dimZeroCounts]
)
return (
@@ -125,6 +128,7 @@ export function Facet({
key={option.value}
option={option}
selected={selected.includes(option.value)}
+ excluded={excluded.includes(option.value)}
slug={slug}
onToggle={onToggle}
dimZeroCounts={dimZeroCounts}
@@ -141,6 +145,7 @@ export function Facet({
interface FacetValueRowProps {
options: FacetOption[]
selected: string[]
+ excluded: string[]
slug: string
onToggle: (value: string) => void
dimZeroCounts: boolean
@@ -152,6 +157,7 @@ function FacetValueRow({
style,
options,
selected,
+ excluded,
slug,
onToggle,
dimZeroCounts,
@@ -167,6 +173,7 @@ function FacetValueRow({
<FacetValueButton
option={option}
selected={selected.includes(option.value)}
+ excluded={excluded.includes(option.value)}
slug={slug}
onToggle={onToggle}
dimZeroCounts={dimZeroCounts}
@@ -178,18 +185,20 @@ function FacetValueRow({
function FacetValueButton({
option,
selected,
+ excluded,
slug,
onToggle,
dimZeroCounts,
}: {
option: FacetOption
selected: boolean
+ excluded: boolean
slug: string
onToggle: (value: string) => void
dimZeroCounts: boolean
}): JSX.Element {
// A fixed facet value with no matches in the current scope: dim it, and disable it unless it's
- // already selected (so a selected-but-now-empty value can still be toggled off).
+ // already selected or excluded (so an active-but-now-empty value can still be cycled off).
const isZero = dimZeroCounts && option.count === 0
return (
<LemonButton
@@ -197,14 +206,24 @@ function FacetValueButton({
size="small"
fullWidth
className={cn(isZero && 'opacity-50')}
- disabledReason={isZero && !selected ? 'No matching spans for the current filters' : undefined}
- icon={<LemonCheckbox checked={selected} className="pointer-events-none" />}
+ disabledReason={isZero && !selected && !excluded ? 'No matching spans for the current filters' : undefined}
+ icon={
+ excluded ? (
+ // Deliberately not LemonCheckbox's `indeterminate` — that means "partially
+ // selected", while this box means "negated".
+ <span className="flex items-center justify-center w-4 h-4 rounded border-[1.5px] border-danger text-danger shrink-0 pointer-events-none">
+ <IconMinusSmall className="text-sm" />
+ </span>
+ ) : (
+ <LemonCheckbox checked={selected} className="pointer-events-none" />
+ )
+ }
onClick={() => onToggle(option.value)}
data-attr={`tracing-facet-${slug}-${slugify(option.value)}`}
>
<span className="flex items-center gap-2 min-w-0 w-full">
{/* Native title so a truncated value is still readable without popover cost per virtualized row. */}
- <span className="truncate flex-1" title={option.label}>
+ <span className={cn('truncate flex-1', excluded && 'line-through text-muted')} title={option.label}>
{option.label}
</span>
{option.count != null && (
diff --git a/products/tracing/frontend/components/FacetRail/FacetRail.tsx b/products/tracing/frontend/components/FacetRail/FacetRail.tsx
index 3e8aac8e890b..6c3b46ce85d2 100644
--- a/products/tracing/frontend/components/FacetRail/FacetRail.tsx
+++ b/products/tracing/frontend/components/FacetRail/FacetRail.tsx
@@ -14,7 +14,7 @@ import { facetRailLogic } from './facetRailLogic'
import {
FacetConfig,
FacetOption,
- facetSelectedValues,
+ facetSelection,
facetsByGroup,
filterFacetsByName,
mergeSelectedIntoOptions,
@@ -53,9 +53,9 @@ export function FacetRail(): JSX.Element {
const renderFacet = (facet: FacetConfig): JSX.Element => {
const { source } = facet
- // Selection: the service facet reads the dedicated serviceNames field; everything else reads
- // its property filter out of the group (see facetSelectedValues).
- const selected = facetSelectedValues(filters.filterGroup, serviceNames, source)
+ // Selection: the service facet reads the dedicated serviceNames field (include-only);
+ // everything else reads its property filters out of the group, both polarities.
+ const { included: selected, excluded } = facetSelection(filters.filterGroup, serviceNames, source)
// Values + counts come from the cross-filtered endpoint, keyed by facet.key. Drop the
// empty-value bucket (spans missing the attribute): it renders as a blank, label-less row
// that the selection reader can't track, so it would become a stuck, un-toggleable filter.
@@ -85,6 +85,7 @@ export function FacetRail(): JSX.Element {
title={facet.title}
options={options}
selected={selected}
+ excluded={excluded}
onToggle={onToggle}
loading={loading}
collapsed={collapsed}
@@ -102,8 +103,9 @@ export function FacetRail(): JSX.Element {
<Facet
key={facet.key}
title={facet.title}
- options={mergeSelectedIntoOptions(fetched, selected, search)}
+ options={mergeSelectedIntoOptions(fetched, [...selected, ...excluded], search)}
selected={selected}
+ excluded={excluded}
onToggle={onToggle}
loading={loading}
emptyLabel={facet.emptyLabel}
diff --git a/products/tracing/frontend/components/FacetRail/facetRailLogic.test.ts b/products/tracing/frontend/components/FacetRail/facetRailLogic.test.ts
index 219ffc36808f..9ac9287a6cd9 100644
--- a/products/tracing/frontend/components/FacetRail/facetRailLogic.test.ts
+++ b/products/tracing/frontend/components/FacetRail/facetRailLogic.test.ts
@@ -5,7 +5,7 @@ import { UniversalFiltersGroup } from '~/types'
import { tracingFiltersLogic } from '../../tracingFiltersLogic'
import { facetRailLogic } from './facetRailLogic'
-import { FacetSource, FilterGroupFacetSource, facetFilterValues } from './facets'
+import { FacetSelection, FacetSource, FilterGroupFacetSource, facetFilterSelection } from './facets'
const SERVICE_SOURCE: FacetSource = { type: 'column', column: 'service_name' }
const STATUS_SOURCE: FilterGroupFacetSource = { type: 'column', column: 'status_code' }
@@ -50,25 +50,31 @@ describe('facetRailLogic', () => {
describe.each<[string, FilterGroupFacetSource]>([
['status column facet', STATUS_SOURCE],
['resource-attribute facet', NAMESPACE_SOURCE],
- ])('%s toggling', (_, source) => {
- const read = (): string[] => facetFilterValues(filtersLogic.values.filterGroup, source)
+ ])('%s cycling', (_, source) => {
+ const read = (): FacetSelection => facetFilterSelection(filtersLogic.values.filterGroup, source)
+ const click = async (value: string): Promise<void> => {
+ await expectLogic(logic, () => logic.actions.toggleFacetValue(source, value)).toFinishAllListeners()
+ }
- it('adds, accumulates (OR), and removes values as a property filter in the group', async () => {
- await expectLogic(logic, () => logic.actions.toggleFacetValue(source, 'a')).toFinishAllListeners()
- expect(read()).toEqual(['a'])
+ it('cycles a value included → excluded → cleared through the shared filters logic', async () => {
+ await click('a')
+ expect(read()).toEqual({ included: ['a'], excluded: [] })
- await expectLogic(logic, () => logic.actions.toggleFacetValue(source, 'b')).toFinishAllListeners()
- expect(read()).toEqual(['a', 'b'])
+ await click('a')
+ expect(read()).toEqual({ included: [], excluded: ['a'] })
- await expectLogic(logic, () => logic.actions.toggleFacetValue(source, 'a')).toFinishAllListeners()
- expect(read()).toEqual(['b'])
+ await click('a')
+ expect(read()).toEqual({ included: [], excluded: [] })
+ expect((filtersLogic.values.filterGroup.values[0] as UniversalFiltersGroup).values).toEqual([])
})
- it('removing the last value drops the filter from the group entirely', async () => {
- await expectLogic(logic, () => logic.actions.toggleFacetValue(source, 'a')).toFinishAllListeners()
- await expectLogic(logic, () => logic.actions.toggleFacetValue(source, 'a')).toFinishAllListeners()
- expect(read()).toEqual([])
- expect((filtersLogic.values.filterGroup.values[0] as UniversalFiltersGroup).values).toEqual([])
+ it('holds one value included while another is excluded', async () => {
+ await click('a')
+ await click('b')
+ expect(read()).toEqual({ included: ['a', 'b'], excluded: [] })
+
+ await click('a')
+ expect(read()).toEqual({ included: ['b'], excluded: ['a'] })
})
})
diff --git a/products/tracing/frontend/components/FacetRail/facetRailLogic.ts b/products/tracing/frontend/components/FacetRail/facetRailLogic.ts
index 4aa4f51857b9..26475ec30de7 100644
--- a/products/tracing/frontend/components/FacetRail/facetRailLogic.ts
+++ b/products/tracing/frontend/components/FacetRail/facetRailLogic.ts
@@ -7,7 +7,7 @@ import {
} from 'products/tracing/frontend/tracingFiltersLogic'
import type { UniversalFiltersGroup } from '../../../../../frontend/src/types'
-import { FacetSource, toggleFacetFilter } from './facets'
+import { FacetSource, cycleFacetFilter } from './facets'
export interface FacetRailLogicProps {
id: string
@@ -111,13 +111,14 @@ export const facetRailLogic = kea<facetRailLogicType>([
actions.setServiceNames(toggleMembership(serviceNames, value))
} else {
// Rebuilt (not passed through) so control flow narrows the column literal past
- // 'service_name', matching toggleFacetFilter's FilterGroupFacetSource contract.
+ // 'service_name', matching cycleFacetFilter's FilterGroupFacetSource contract.
+ // A click cycles the value included → excluded → cleared.
actions.setFilterGroup(
- toggleFacetFilter(filterGroup, { type: 'column', column: source.column }, value)
+ cycleFacetFilter(filterGroup, { type: 'column', column: source.column }, value)
)
}
} else {
- actions.setFilterGroup(toggleFacetFilter(filterGroup, source, value))
+ actions.setFilterGroup(cycleFacetFilter(filterGroup, source, value))
}
},
})),
diff --git a/products/tracing/frontend/components/FacetRail/facets.test.ts b/products/tracing/frontend/components/FacetRail/facets.test.ts
index d1c1002529dd..e39d33e2db74 100644
--- a/products/tracing/frontend/components/FacetRail/facets.test.ts
+++ b/products/tracing/frontend/components/FacetRail/facets.test.ts
@@ -2,13 +2,14 @@ import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalF
import {
FACETS,
+ FacetSelection,
FacetSource,
FilterGroupFacetSource,
- facetFilterValues,
- facetSelectedValues,
+ cycleFacetFilter,
+ facetFilterSelection,
+ facetSelection,
mergeSelectedIntoOptions,
resolveFacets,
- toggleFacetFilter,
} from './facets'
const SERVICE_SOURCE: FacetSource = { type: 'column', column: 'service_name' }
@@ -24,7 +25,10 @@ function groupWith(values: object[]): UniversalFiltersGroup {
}
describe('facets', () => {
- describe('toggleFacetFilter / facetFilterValues', () => {
+ describe('cycleFacetFilter / facetFilterSelection', () => {
+ const read = (group: UniversalFiltersGroup | undefined, source: FilterGroupFacetSource): FacetSelection =>
+ facetFilterSelection(group, source)
+
it.each<[string, FilterGroupFacetSource, PropertyFilterType]>([
['column facet writes a span filter', STATUS_SOURCE, PropertyFilterType.Span],
[
@@ -33,26 +37,34 @@ describe('facets', () => {
PropertyFilterType.SpanResourceAttribute,
],
])('%s', (_, source, expectedType) => {
- const group = toggleFacetFilter(undefined, source, 'a')
+ const group = cycleFacetFilter(undefined, source, 'a')
const inner = (group.values[0] as UniversalFiltersGroup).values
expect(inner).toEqual([
expect.objectContaining({ type: expectedType, operator: PropertyOperator.Exact, value: ['a'] }),
])
- expect(facetFilterValues(group, source)).toEqual(['a'])
+ expect(read(group, source)).toEqual({ included: ['a'], excluded: [] })
})
- it('accumulates values on repeated toggles and removes on re-toggle', () => {
- let group = toggleFacetFilter(undefined, POD_SOURCE, 'pod-a')
- group = toggleFacetFilter(group, POD_SOURCE, 'pod-b')
- expect(facetFilterValues(group, POD_SOURCE)).toEqual(['pod-a', 'pod-b'])
+ it('cycles a value unchecked → included → excluded → unchecked, dropping emptied filters', () => {
+ const afterFirst = cycleFacetFilter(undefined, POD_SOURCE, 'pod-a')
+ expect(read(afterFirst, POD_SOURCE)).toEqual({ included: ['pod-a'], excluded: [] })
+
+ const afterSecond = cycleFacetFilter(afterFirst, POD_SOURCE, 'pod-a')
+ expect(read(afterSecond, POD_SOURCE)).toEqual({ included: [], excluded: ['pod-a'] })
- group = toggleFacetFilter(group, POD_SOURCE, 'pod-a')
- expect(facetFilterValues(group, POD_SOURCE)).toEqual(['pod-b'])
+ const afterThird = cycleFacetFilter(afterSecond, POD_SOURCE, 'pod-a')
+ expect((afterThird.values[0] as UniversalFiltersGroup).values).toEqual([])
})
- it('drops the filter entirely when the last value is toggled off', () => {
- const group = toggleFacetFilter(toggleFacetFilter(undefined, POD_SOURCE, 'pod-a'), POD_SOURCE, 'pod-a')
- expect((group.values[0] as UniversalFiltersGroup).values).toEqual([])
+ it('writes includes as an exact filter and excludes as an is_not filter, both array-valued', () => {
+ let group = cycleFacetFilter(undefined, POD_SOURCE, 'pod-a')
+ group = cycleFacetFilter(group, POD_SOURCE, 'pod-b')
+ group = cycleFacetFilter(group, POD_SOURCE, 'pod-a') // pod-a → excluded
+
+ expect((group.values[0] as UniversalFiltersGroup).values).toEqual([
+ expect.objectContaining({ operator: PropertyOperator.Exact, value: ['pod-b'] }),
+ expect.objectContaining({ operator: PropertyOperator.IsNot, value: ['pod-a'] }),
+ ])
})
it('preserves unrelated filters, including a same-key filter of a different type', () => {
@@ -64,42 +76,51 @@ describe('facets', () => {
operator: PropertyOperator.IContains,
value: 'pod',
}
- const group = toggleFacetFilter(groupWith([other]), POD_SOURCE, 'pod-a')
+ const group = cycleFacetFilter(groupWith([other]), POD_SOURCE, 'pod-a')
const inner = (group.values[0] as UniversalFiltersGroup).values
expect(inner).toEqual([other, expect.objectContaining({ type: PropertyFilterType.SpanResourceAttribute })])
- expect(facetFilterValues(group, POD_SOURCE)).toEqual(['pod-a'])
+ expect(read(group, POD_SOURCE)).toEqual({ included: ['pod-a'], excluded: [] })
})
- it('reads a scalar filter value written outside the rail as a single selection', () => {
- const group = groupWith([
- {
- key: 'status_code',
- type: PropertyFilterType.Span,
- operator: PropertyOperator.Exact,
- value: 'Error',
- },
- ])
- expect(facetFilterValues(group, STATUS_SOURCE)).toEqual(['Error'])
- })
-
- it('drops empty strings written by external state so they cannot become stuck filters', () => {
- const group = groupWith([
- {
- key: 'status_code',
- type: PropertyFilterType.Span,
- operator: PropertyOperator.Exact,
- value: ['Error', ''],
- },
- ])
- expect(facetFilterValues(group, STATUS_SOURCE)).toEqual(['Error'])
+ it.each<[string, PropertyOperator, unknown, FacetSelection]>([
+ [
+ 'a scalar exact chip written outside the rail reads as a single inclusion',
+ PropertyOperator.Exact,
+ 'Error',
+ { included: ['Error'], excluded: [] },
+ ],
+ [
+ 'a scalar is_not chip written outside the rail reads as a single exclusion',
+ PropertyOperator.IsNot,
+ 'Error',
+ { included: [], excluded: ['Error'] },
+ ],
+ [
+ 'empty strings from external state are dropped so they cannot become stuck filters',
+ PropertyOperator.Exact,
+ ['Error', ''],
+ { included: ['Error'], excluded: [] },
+ ],
+ [
+ 'a non-rail operator chip is not rail state',
+ PropertyOperator.IContains,
+ 'Error',
+ { included: [], excluded: [] },
+ ],
+ ])('%s', (_, operator, value, expected) => {
+ const group = groupWith([{ key: 'status_code', type: PropertyFilterType.Span, operator, value }])
+ expect(read(group, STATUS_SOURCE)).toEqual(expected)
})
})
- describe('facetSelectedValues', () => {
+ describe('facetSelection', () => {
it('drops empty service names from external state so they cannot inject a blank row', () => {
// The service facet reads the dedicated serviceNames field, not the filterGroup — a URL or
// saved view carrying serviceNames: [''] must not surface a blank selected service row.
- expect(facetSelectedValues(undefined, ['api', ''], SERVICE_SOURCE)).toEqual(['api'])
+ expect(facetSelection(undefined, ['api', ''], SERVICE_SOURCE)).toEqual({
+ included: ['api'],
+ excluded: [],
+ })
})
})
diff --git a/products/tracing/frontend/components/FacetRail/facets.ts b/products/tracing/frontend/components/FacetRail/facets.ts
index b3ebc9434d02..fcb2fbc4d627 100644
--- a/products/tracing/frontend/components/FacetRail/facets.ts
+++ b/products/tracing/frontend/components/FacetRail/facets.ts
@@ -92,17 +92,31 @@ function facetFilterKey(source: FilterGroupFacetSource): string {
return source.type === 'column' ? source.column : source.key
}
-function isFacetFilter(filter: SpanFacetFilter, source: FilterGroupFacetSource): boolean {
- return filter?.type === facetFilterType(source) && filter?.key === facetFilterKey(source)
-}
-
/**
- * Values currently selected for a facet whose selection lives in the filterGroup (status_code and
- * resource attributes — service_name reads the dedicated serviceNames field instead).
+ * Tri-state selection for a facet: a value is included, excluded, or in neither set. The query
+ * effect is `IN (included)` AND `NOT IN (excluded)` — attribute exclusions keep spans missing the
+ * attribute entirely (an absent map key reads as '', which never equals an excluded value).
*/
-export function facetFilterValues(group: UniversalFiltersGroup | undefined, source: FilterGroupFacetSource): string[] {
- const existing = innerFilters(group).find((f) => isFacetFilter(f, source))
- const value = existing?.value
+export interface FacetSelection {
+ included: string[]
+ excluded: string[]
+}
+
+// The rail owns a facet's `exact` (include) and `is_not` (exclude) filters. A chip on the same key
+// with any other operator (e.g. icontains) is not rail state: it's ignored on read and preserved
+// untouched on write.
+const RAIL_OPERATORS: PropertyOperator[] = [PropertyOperator.Exact, PropertyOperator.IsNot]
+
+function isRailFacetFilter(filter: SpanFacetFilter, source: FilterGroupFacetSource): boolean {
+ return (
+ filter?.type === facetFilterType(source) &&
+ filter?.key === facetFilterKey(source) &&
+ RAIL_OPERATORS.includes(filter?.operator)
+ )
+}
+
+function filterValues(filter: SpanFacetFilter): string[] {
+ const value = filter.value
if (Array.isArray(value)) {
// Empty strings from external state (URL, saved view) would select a value with no visible row.
return value.map(String).filter((v) => v !== '')
@@ -111,48 +125,79 @@ export function facetFilterValues(group: UniversalFiltersGroup | undefined, sour
}
/**
- * Values currently selected for any facet — routes the service facet to the dedicated
- * serviceNames field and everything else to its filterGroup property filter.
+ * Selection for a facet whose state lives in the filterGroup (status_code and resource attributes —
+ * service_name reads the dedicated serviceNames field instead), read from its exact (include) and
+ * is_not (exclude) filters.
+ */
+export function facetFilterSelection(
+ group: UniversalFiltersGroup | undefined,
+ source: FilterGroupFacetSource
+): FacetSelection {
+ const railFilters = innerFilters(group).filter((f) => isRailFacetFilter(f, source))
+ return {
+ included: railFilters.filter((f) => f.operator === PropertyOperator.Exact).flatMap(filterValues),
+ excluded: railFilters.filter((f) => f.operator === PropertyOperator.IsNot).flatMap(filterValues),
+ }
+}
+
+/**
+ * Selection for any facet — routes the service facet to the dedicated serviceNames field
+ * (include-only, so nothing is ever excluded there) and everything else to its filterGroup filters.
*/
-export function facetSelectedValues(
+export function facetSelection(
group: UniversalFiltersGroup | undefined,
serviceNames: string[] | undefined | null,
source: FacetSource
-): string[] {
+): FacetSelection {
if (source.type === 'column') {
if (source.column === 'service_name') {
// Empty strings from external state (URL, saved view) would select a value with no visible row.
- return (serviceNames ?? []).filter((v) => v !== '')
+ return { included: (serviceNames ?? []).filter((v) => v !== ''), excluded: [] }
}
- return facetFilterValues(group, { type: 'column', column: source.column })
+ return facetFilterSelection(group, { type: 'column', column: source.column })
}
- return facetFilterValues(group, source)
+ return facetFilterSelection(group, source)
}
/**
- * Add or remove `value` from a facet's filterGroup selection, returning a new filterGroup.
- * Multi-select is one property filter per key with an array value.
+ * Advance `value` one step through the facet cycle — unchecked → included → excluded → unchecked —
+ * returning a new filterGroup. Selection is stored as up to two property filters per key with
+ * array values, `exact` and `is_not`; a filter is dropped when its side of the selection empties.
*/
-export function toggleFacetFilter(
+export function cycleFacetFilter(
group: UniversalFiltersGroup | undefined,
source: FilterGroupFacetSource,
value: string
): UniversalFiltersGroup {
- const current = facetFilterValues(group, source)
- const next = current.includes(value) ? current.filter((v) => v !== value) : [...current, value]
- const others = innerFilters(group).filter((f) => !isFacetFilter(f, source))
- const values: SpanFacetFilter[] =
- next.length > 0
- ? [
- ...others,
- {
- key: facetFilterKey(source),
- type: facetFilterType(source),
- operator: PropertyOperator.Exact,
- value: next,
- },
- ]
- : others
+ const { included, excluded } = facetFilterSelection(group, source)
+ let nextIncluded = included
+ let nextExcluded = excluded
+ if (included.includes(value)) {
+ nextIncluded = included.filter((v) => v !== value)
+ nextExcluded = excluded.includes(value) ? excluded : [...excluded, value]
+ } else if (excluded.includes(value)) {
+ nextExcluded = excluded.filter((v) => v !== value)
+ } else {
+ nextIncluded = [...included, value]
+ }
+
+ const values = innerFilters(group).filter((f) => !isRailFacetFilter(f, source))
+ if (nextIncluded.length > 0) {
+ values.push({
+ key: facetFilterKey(source),
+ type: facetFilterType(source),
+ operator: PropertyOperator.Exact,
+ value: nextIncluded,
+ })
+ }
+ if (nextExcluded.length > 0) {
+ values.push({
+ key: facetFilterKey(source),
+ type: facetFilterType(source),
+ operator: PropertyOperator.IsNot,
+ value: nextExcluded,
+ })
+ }
return { type: FilterLogicalOperator.And, values: [{ type: FilterLogicalOperator.And, values }] }
}