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): render facet rail values and wire selections into filters (#69875)

Jon McCallum100f1cf58f74
diff --git a/products/tracing/frontend/components/FacetRail/Facet.tsx b/products/tracing/frontend/components/FacetRail/Facet.tsx
new file mode 100644
index 000000000000..9b15a8d0d0f7
--- /dev/null
+++ b/products/tracing/frontend/components/FacetRail/Facet.tsx
@@ -0,0 +1,120 @@
+import { IconChevronDown, IconChevronRight } from '@posthog/icons'
+import { LemonButton, LemonCheckbox } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+import { FacetOption } from './facets'
+
+interface FacetProps {
+ title: string
+ options: FacetOption[]
+ selected: string[]
+ onToggle: (value: string) => void
+ loading?: boolean
+ emptyLabel?: string
+ collapsed?: boolean
+ onToggleCollapsed?: () => void
+ /** For fixed facets: render zero-count values dimmed, and disabled unless already selected. */
+ dimZeroCounts?: boolean
+}
+
+/**
+ * Lowercase a label into a selector-safe slug for data-attrs. Facet values are real resource
+ * attributes (pod, deployment, host names) that can carry spaces, quotes, or slashes, so collapse
+ * any run of non-alphanumerics to a single hyphen and trim the ends.
+ */
+function slugify(value: string): string {
+ return value
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+}
+
+/** A single rail facet: a collapsible field title and its selectable values (multi-select = OR), each with a count. */
+export function Facet({
+ title,
+ options,
+ selected,
+ onToggle,
+ loading = false,
+ emptyLabel = 'No values',
+ collapsed = false,
+ onToggleCollapsed,
+ dimZeroCounts = false,
+}: FacetProps): JSX.Element {
+ const slug = slugify(title)
+
+ return (
+ <div className="mb-3">
+ <button
+ type="button"
+ onClick={onToggleCollapsed}
+ disabled={!onToggleCollapsed}
+ className="flex items-center gap-1 w-full px-1 mb-1 text-[10px] font-semibold uppercase tracking-wide text-secondary hover:text-default"
+ data-attr={`tracing-facet-${slug}-header`}
+ >
+ {collapsed ? <IconChevronRight /> : <IconChevronDown />}
+ <span>{title}</span>
+ </button>
+ {!collapsed &&
+ (loading && options.length === 0 ? (
+ <div className="px-1 text-xs text-muted">Loading…</div>
+ ) : options.length === 0 ? (
+ <div className="px-1 text-xs text-muted">{emptyLabel}</div>
+ ) : (
+ // Dim the list while a refetch is in flight so there's feedback that results
+ // are updating, rather than the list silently changing.
+ <div className={cn('space-y-px', loading && 'opacity-60 transition-opacity')}>
+ {options.map((option) => (
+ <FacetValueButton
+ key={option.value}
+ option={option}
+ selected={selected.includes(option.value)}
+ slug={slug}
+ onToggle={onToggle}
+ dimZeroCounts={dimZeroCounts}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function FacetValueButton({
+ option,
+ selected,
+ slug,
+ onToggle,
+ dimZeroCounts,
+}: {
+ option: FacetOption
+ selected: 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).
+ const isZero = dimZeroCounts && option.count === 0
+ return (
+ <LemonButton
+ type="tertiary"
+ 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" />}
+ onClick={() => onToggle(option.value)}
+ data-attr={`tracing-facet-${slug}-${slugify(option.value)}`}
+ >
+ <span className="flex items-center gap-2 min-w-0 w-full">
+ <span className="truncate flex-1">{option.label}</span>
+ {option.count != null && (
+ <span className="shrink-0 text-muted tabular-nums">{humanFriendlyLargeNumber(option.count)}</span>
+ )}
+ </span>
+ </LemonButton>
+ )
+}
diff --git a/products/tracing/frontend/components/FacetRail/FacetRail.tsx b/products/tracing/frontend/components/FacetRail/FacetRail.tsx
index 37276112cffd..b3e3c4dce030 100644
--- a/products/tracing/frontend/components/FacetRail/FacetRail.tsx
+++ b/products/tracing/frontend/components/FacetRail/FacetRail.tsx
@@ -1,21 +1,36 @@
import { useActions, useValues } from 'kea'
import { useCallback, useMemo, useRef } from 'react'
+import { LemonInput } from '@posthog/lemon-ui'
+
import { Resizer } from 'lib/components/Resizer/Resizer'
import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
import { tracingConfigLogic } from '../../tracingConfigLogic'
+import { tracingFiltersLogic } from '../../tracingFiltersLogic'
+import { Facet } from './Facet'
+import { facetCountsLogic } from './facetCountsLogic'
+import { facetRailLogic } from './facetRailLogic'
+import {
+ FacetConfig,
+ FacetOption,
+ facetSelectedValues,
+ facetsByGroup,
+ filterFacetsByName,
+ mergeSelectedIntoOptions,
+} from './facets'
const DEFAULT_WIDTH_PX = 240
const COLLAPSE_THRESHOLD_PX = 120
-/**
- * Resizable left-hand facet rail for the tracing scene. Facets (values + counts) land in
- * follow-up PRs — this is the flag-gated shell: sizing, persistence, and collapse behavior.
- */
+/** Resizable left-hand facet rail, rendered entirely from the FACETS config (see facets.ts). */
export function FacetRail(): JSX.Element {
const railRef = useRef<HTMLDivElement>(null)
const { setFacetRailCollapsed } = useActions(tracingConfigLogic)
+ const { serviceNames, filters } = useValues(tracingFiltersLogic)
+ const { facetValues, facetValuesLoading, visibleFacets } = useValues(facetCountsLogic)
+ const { collapsedFacets, facetNameSearch } = useValues(facetRailLogic)
+ const { toggleFacetValue, toggleFacetCollapsed, setFacetNameSearch } = useActions(facetRailLogic)
const onToggleClosed = useCallback(
(shouldBeClosed: boolean) => setFacetRailCollapsed(shouldBeClosed),
@@ -35,6 +50,67 @@ export function FacetRail(): JSX.Element {
)
const { desiredSize } = useValues(resizerLogic(resizerLogicProps))
+ 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)
+ // 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.
+ const fetched: FacetOption[] = (facetValues[facet.key] ?? [])
+ .filter((row) => row.value !== '')
+ .map((row) => ({
+ value: row.value,
+ label: row.value,
+ count: row.count,
+ }))
+ const onToggle = (value: string): void => toggleFacetValue(source, value)
+ const onToggleCollapsed = (): void => toggleFacetCollapsed(facet.key)
+ const collapsed = collapsedFacets.includes(facet.key)
+
+ if (facet.kind === 'fixed') {
+ // Fixed value set from config, counts overlaid. Missing values render as a dimmed 0.
+ const countByValue = new Map(fetched.map((option) => [option.value, option.count]))
+ const options: FacetOption[] = (facet.fixedOptions ?? []).map((option) => ({
+ ...option,
+ count: countByValue.get(option.value) ?? 0,
+ }))
+ return (
+ <Facet
+ key={facet.key}
+ title={facet.title}
+ options={options}
+ selected={selected}
+ onToggle={onToggle}
+ loading={facetValuesLoading}
+ collapsed={collapsed}
+ onToggleCollapsed={onToggleCollapsed}
+ dimZeroCounts
+ />
+ )
+ }
+
+ // Dynamic facet: values + counts come straight from the cross-filtered endpoint (zeros never
+ // appear), with any selected-but-absent values injected so they stay visible and toggleable.
+ return (
+ <Facet
+ key={facet.key}
+ title={facet.title}
+ options={mergeSelectedIntoOptions(fetched, selected)}
+ selected={selected}
+ onToggle={onToggle}
+ loading={facetValuesLoading}
+ emptyLabel={facet.emptyLabel}
+ collapsed={collapsed}
+ onToggleCollapsed={onToggleCollapsed}
+ />
+ )
+ }
+
+ // Filter the rail by the field-name search, then group — empty groups fall away in facetsByGroup.
+ const displayedGroups = facetsByGroup(filterFacetsByName(visibleFacets, facetNameSearch))
+
return (
<div
ref={railRef}
@@ -43,8 +119,30 @@ export function FacetRail(): JSX.Element {
style={{ width: desiredSize ?? DEFAULT_WIDTH_PX, minWidth: 'min-content', maxWidth: '40%' }}
data-attr="tracing-facet-rail"
>
+ <div className="px-2 py-1 border-b">
+ <LemonInput
+ type="search"
+ size="small"
+ fullWidth
+ placeholder="Search facets…"
+ value={facetNameSearch}
+ onChange={setFacetNameSearch}
+ data-attr="tracing-facet-rail-search"
+ />
+ </div>
<div className="flex-1 min-h-0 overflow-y-auto p-2">
- <div className="px-1 text-xs text-muted">Facets will appear here.</div>
+ {displayedGroups.length === 0 && facetNameSearch.trim() ? (
+ <div className="px-1 text-xs text-muted">No matching facets</div>
+ ) : (
+ displayedGroups.map(([group, facets]) => (
+ <div key={group}>
+ <div className="px-1 pb-1 mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted border-b border-primary">
+ {group}
+ </div>
+ {facets.map(renderFacet)}
+ </div>
+ ))
+ )}
</div>
<Resizer {...resizerLogicProps} visible={false} offset="0.25rem" handleClassName="rounded my-1" />
</div>
diff --git a/products/tracing/frontend/components/FacetRail/facetRailLogic.test.ts b/products/tracing/frontend/components/FacetRail/facetRailLogic.test.ts
new file mode 100644
index 000000000000..219ffc36808f
--- /dev/null
+++ b/products/tracing/frontend/components/FacetRail/facetRailLogic.test.ts
@@ -0,0 +1,88 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+import { UniversalFiltersGroup } from '~/types'
+
+import { tracingFiltersLogic } from '../../tracingFiltersLogic'
+import { facetRailLogic } from './facetRailLogic'
+import { FacetSource, FilterGroupFacetSource, facetFilterValues } from './facets'
+
+const SERVICE_SOURCE: FacetSource = { type: 'column', column: 'service_name' }
+const STATUS_SOURCE: FilterGroupFacetSource = { type: 'column', column: 'status_code' }
+const NAMESPACE_SOURCE: FilterGroupFacetSource = { type: 'resourceAttribute', key: 'k8s.namespace.name' }
+
+describe('facetRailLogic', () => {
+ let filtersLogic: ReturnType<typeof tracingFiltersLogic.build>
+ let logic: ReturnType<typeof facetRailLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ filtersLogic = tracingFiltersLogic({ id: 'test' })
+ filtersLogic.mount()
+ logic = facetRailLogic({ id: 'test' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ filtersLogic.unmount()
+ })
+
+ describe('service toggling', () => {
+ it('routes to the dedicated serviceNames field, never the filterGroup', async () => {
+ await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
+ expect(filtersLogic.values.serviceNames).toEqual(['api'])
+ // The span queries read serviceNames — a filterGroup entry would silently not filter.
+ expect((filtersLogic.values.filterGroup.values[0] as UniversalFiltersGroup).values).toEqual([])
+
+ await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
+ expect(filtersLogic.values.serviceNames).toEqual([])
+ })
+
+ it('toggles relative to services already selected outside the rail', async () => {
+ filtersLogic.actions.setServiceNames(['worker'])
+
+ await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
+ expect(filtersLogic.values.serviceNames).toEqual(['worker', 'api'])
+ })
+ })
+
+ 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)
+
+ 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'])
+
+ await expectLogic(logic, () => logic.actions.toggleFacetValue(source, 'b')).toFinishAllListeners()
+ expect(read()).toEqual(['a', 'b'])
+
+ await expectLogic(logic, () => logic.actions.toggleFacetValue(source, 'a')).toFinishAllListeners()
+ expect(read()).toEqual(['b'])
+ })
+
+ 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([])
+ })
+ })
+
+ describe('facet collapse', () => {
+ it('adds a facet to the collapsed set, then removes it on the second toggle', () => {
+ logic.actions.toggleFacetCollapsed('service')
+ expect(logic.values.collapsedFacets).toContain('service')
+
+ logic.actions.toggleFacetCollapsed('status')
+ expect(logic.values.collapsedFacets).toEqual(expect.arrayContaining(['service', 'status']))
+
+ logic.actions.toggleFacetCollapsed('service')
+ expect(logic.values.collapsedFacets).not.toContain('service')
+ expect(logic.values.collapsedFacets).toContain('status')
+ })
+ })
+})
diff --git a/products/tracing/frontend/components/FacetRail/facetRailLogic.ts b/products/tracing/frontend/components/FacetRail/facetRailLogic.ts
new file mode 100644
index 000000000000..6ceca144b8ce
--- /dev/null
+++ b/products/tracing/frontend/components/FacetRail/facetRailLogic.ts
@@ -0,0 +1,83 @@
+import { actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
+
+import {
+ TRACING_SCENE_VIEWER_ID,
+ tracingFiltersLogic,
+ TracingFiltersLogicProps,
+} from 'products/tracing/frontend/tracingFiltersLogic'
+
+import type { facetRailLogicType } from './facetRailLogicType'
+import { FacetSource, toggleFacetFilter } from './facets'
+
+export interface FacetRailLogicProps {
+ id: string
+}
+
+function toggleMembership(values: readonly string[] | undefined | null, value: string): string[] {
+ const current = values ?? []
+ return current.includes(value) ? current.filter((v) => v !== value) : [...current, value]
+}
+
+// The rail is a lens over the existing filter model — facet toggles write straight back to
+// tracingFiltersLogic's reducers, so URL sync, saved views, and the filter chips stay in step.
+export const facetRailLogic = kea<facetRailLogicType>([
+ path(['products', 'tracing', 'frontend', 'components', 'FacetRail', 'facetRailLogic']),
+ props({ id: TRACING_SCENE_VIEWER_ID } as FacetRailLogicProps),
+ key((props) => props.id),
+
+ connect((props: FacetRailLogicProps) => ({
+ actions: [
+ tracingFiltersLogic({ id: props.id } as TracingFiltersLogicProps),
+ ['setServiceNames', 'setFilterGroup'],
+ ],
+ })),
+
+ actions({
+ // Generic toggle: the rail is config-driven, so a single action writes a value into whichever
+ // filter field/group the facet's source maps to (see FacetConfig.source).
+ toggleFacetValue: (source: FacetSource, value: string) => ({ source, value }),
+ toggleFacetCollapsed: (facetKey: string) => ({ facetKey }),
+ // Free-text filter over the facet *fields* shown in the rail (not their values).
+ setFacetNameSearch: (search: string) => ({ search }),
+ }),
+
+ reducers({
+ facetNameSearch: [
+ '',
+ {
+ setFacetNameSearch: (_, { search }) => search,
+ },
+ ],
+ collapsedFacets: [
+ [] as string[],
+ { persist: true },
+ {
+ toggleFacetCollapsed: (state, { facetKey }) =>
+ state.includes(facetKey) ? state.filter((k) => k !== facetKey) : [...state, facetKey],
+ },
+ ],
+ }),
+
+ listeners(({ props, actions }) => ({
+ toggleFacetValue: ({ source, value }) => {
+ const { serviceNames, filterGroup } = tracingFiltersLogic({
+ id: props.id,
+ } as TracingFiltersLogicProps).values
+ if (source.type === 'column') {
+ if (source.column === 'service_name') {
+ // Service selection lives in the dedicated serviceNames field the span queries
+ // read, not in the filterGroup (see FilterGroupFacetSource).
+ 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.
+ actions.setFilterGroup(
+ toggleFacetFilter(filterGroup, { type: 'column', column: source.column }, value)
+ )
+ }
+ } else {
+ actions.setFilterGroup(toggleFacetFilter(filterGroup, source, value))
+ }
+ },
+ })),
+])
diff --git a/products/tracing/frontend/components/FacetRail/facets.test.ts b/products/tracing/frontend/components/FacetRail/facets.test.ts
index 574f0cf38fbb..d59fbb443389 100644
--- a/products/tracing/frontend/components/FacetRail/facets.test.ts
+++ b/products/tracing/frontend/components/FacetRail/facets.test.ts
@@ -1,6 +1,6 @@
import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
-import { FilterGroupFacetSource, facetFilterValues, toggleFacetFilter } from './facets'
+import { FilterGroupFacetSource, facetFilterValues, mergeSelectedIntoOptions, toggleFacetFilter } from './facets'
const STATUS_SOURCE: FilterGroupFacetSource = { type: 'column', column: 'status_code' }
const POD_SOURCE: FilterGroupFacetSource = { type: 'resourceAttribute', key: 'k8s.pod.name' }
@@ -70,5 +70,40 @@ describe('facets', () => {
])
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'])
+ })
+ })
+
+ describe('mergeSelectedIntoOptions', () => {
+ it('prepends a selected value absent from the fetched list with a zero count', () => {
+ const fetched = [{ value: 'api', label: 'api', count: 5 }]
+ expect(mergeSelectedIntoOptions(fetched, ['worker'])).toEqual([
+ { value: 'worker', label: 'worker', count: 0 },
+ { value: 'api', label: 'api', count: 5 },
+ ])
+ })
+
+ it('collapses duplicate selected values into one row so keys never collide', () => {
+ // A URL or saved view can carry the same value twice; two rows sharing a value would
+ // collide on their React key and toggle target.
+ expect(mergeSelectedIntoOptions([], ['worker', 'worker'])).toEqual([
+ { value: 'worker', label: 'worker', count: 0 },
+ ])
+ })
+
+ it('does not re-add a selected value already present in the fetched list', () => {
+ const fetched = [{ value: 'api', label: 'api', count: 5 }]
+ expect(mergeSelectedIntoOptions(fetched, ['api'])).toEqual(fetched)
+ })
})
})
diff --git a/products/tracing/frontend/components/FacetRail/facets.ts b/products/tracing/frontend/components/FacetRail/facets.ts
index a56f79b336f6..b7311ccfcaf2 100644
--- a/products/tracing/frontend/components/FacetRail/facets.ts
+++ b/products/tracing/frontend/components/FacetRail/facets.ts
@@ -100,11 +100,30 @@ export function facetFilterValues(group: UniversalFiltersGroup | undefined, sour
const existing = innerFilters(group).find((f) => isFacetFilter(f, source))
const value = existing?.value
if (Array.isArray(value)) {
- return value.map(String)
+ // Empty strings from external state (URL, saved view) would select a value with no visible row.
+ return value.map(String).filter((v) => v !== '')
}
return value != null && value !== '' ? [String(value)] : []
}
+/**
+ * Values currently selected for any facet — routes the service facet to the dedicated
+ * serviceNames field and everything else to its filterGroup property filter.
+ */
+export function facetSelectedValues(
+ group: UniversalFiltersGroup | undefined,
+ serviceNames: string[] | undefined | null,
+ source: FacetSource
+): string[] {
+ if (source.type === 'column') {
+ if (source.column === 'service_name') {
+ return serviceNames ?? []
+ }
+ return facetFilterValues(group, { type: 'column', column: source.column })
+ }
+ return facetFilterValues(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.
@@ -203,5 +222,52 @@ export const FACETS: FacetConfig[] = [
HOST_FACET,
]
-// List-shaping helpers for rendering the rail (grouping, name search, merging selected values
-// into fetched options) land with their consumer, the Facet/FacetRail components.
+/**
+ * Filter facets by a free-text query matching the field name or its group (case-insensitive
+ * substring) — powers the rail's "search facets" box. A blank query returns everything, so
+ * `facetsByGroup` then drops any group left with no matching facets for free.
+ */
+export function filterFacetsByName(facets: FacetConfig[], query: string): FacetConfig[] {
+ const needle = query.trim().toLowerCase()
+ if (!needle) {
+ return facets
+ }
+ return facets.filter(
+ (facet) => facet.title.toLowerCase().includes(needle) || facet.group.toLowerCase().includes(needle)
+ )
+}
+
+/**
+ * Ensure every selected value of a dynamic facet renders even when absent from the fetched list —
+ * a filter from a URL or saved view can reference a value with no matches in the current scope
+ * (or one below the top-N cutoff), and without a visible row it can't be seen or toggled off.
+ * Missing values are prepended with a zero count.
+ */
+export function mergeSelectedIntoOptions(fetched: FacetOption[], selected: string[]): FacetOption[] {
+ const seen = new Set(fetched.map((option) => option.value))
+ // Dedupe as we go: a URL or saved view can carry the same value twice, and two rows sharing a
+ // value would collide on their React key and toggle target.
+ const missing: FacetOption[] = []
+ for (const value of selected) {
+ if (seen.has(value)) {
+ continue
+ }
+ seen.add(value)
+ missing.push({ value, label: value, count: 0 })
+ }
+ return missing.length > 0 ? [...missing, ...fetched] : fetched
+}
+
+/** Group facets by `group`, preserving first-appearance order of both groups and facets. */
+export function facetsByGroup(facets: FacetConfig[]): [string, FacetConfig[]][] {
+ const groups: [string, FacetConfig[]][] = []
+ for (const facet of facets) {
+ const existing = groups.find(([group]) => group === facet.group)
+ if (existing) {
+ existing[1].push(facet)
+ } else {
+ groups.push([facet.group, [facet]])
+ }
+ }
+ return groups
+}