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.

chore(logs): share one facet rail between logs and tracing (#117341)

Daniel Visca3d1a2dc17355
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx b/frontend/src/lib/components/FacetRail/Facet.tsx
similarity index 82%
rename from products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx
rename to frontend/src/lib/components/FacetRail/Facet.tsx
index 92cfb4114000..f34d59c5d72e 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx
+++ b/frontend/src/lib/components/FacetRail/Facet.tsx
@@ -14,7 +14,7 @@ export interface FacetOption {
label: string
/** Tailwind bg class for a leading color swatch (e.g. severity colors). */
color?: string
- /** Number of matching log records; rendered right-aligned. Omitted when unavailable. */
+ /** Number of matching records; rendered right-aligned. Omitted when unavailable. */
count?: number
}
@@ -25,6 +25,9 @@ interface FacetProps {
/** Values in the excluded state — matching records are filtered out. Disjoint from `selected`. */
excluded?: string[]
onToggle: (value: string) => void
+ /** Prefix for every data-attr in the facet, e.g. `logs-facet`. These are frozen: autocapture and tests select on them. */
+ dataAttrPrefix: string
+ zeroCountReason: string
loading?: boolean
emptyLabel?: string
/** When provided, renders a search box above the values (state owned by the caller). */
@@ -47,6 +50,18 @@ interface FacetProps {
onRetry?: () => void
}
+/**
+ * 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,
@@ -54,6 +69,8 @@ export function Facet({
selected,
excluded = [],
onToggle,
+ dataAttrPrefix,
+ zeroCountReason,
loading = false,
emptyLabel = 'No values',
searchValue,
@@ -68,12 +85,12 @@ export function Facet({
onRemove,
removeDisabledReason,
}: FacetProps): JSX.Element {
- const slug = title.toLowerCase().replace(/\s+/g, '-')
+ const dataAttr = `${dataAttrPrefix}-${slugify(title)}`
const errorMessage = options.length > 0 ? "Couldn't refresh values." : "Couldn't load values."
const rowProps = useMemo<FacetValueRowProps>(
- () => ({ options, selected, excluded, slug, onToggle, dimZeroCounts }),
- [options, selected, excluded, slug, onToggle, dimZeroCounts]
+ () => ({ options, selected, excluded, dataAttr, onToggle, dimZeroCounts, zeroCountReason }),
+ [options, selected, excluded, dataAttr, onToggle, dimZeroCounts, zeroCountReason]
)
return (
@@ -84,7 +101,7 @@ export function Facet({
onClick={onToggleCollapsed}
disabled={!onToggleCollapsed}
className="flex items-center gap-1 flex-1 min-w-0 text-[10px] font-semibold uppercase tracking-wide text-secondary hover:text-default"
- data-attr={`logs-facet-${slug}-header`}
+ data-attr={`${dataAttr}-header`}
>
{collapsed ? <IconChevronRight /> : <IconChevronDown />}
<span className="truncate">{title}</span>
@@ -101,7 +118,7 @@ export function Facet({
onClick={onRemove}
disabledReason={removeDisabledReason}
tooltip="Remove custom facet"
- data-attr={`logs-facet-${slug}-remove`}
+ data-attr={`${dataAttr}-remove`}
/>
)}
</div>
@@ -119,10 +136,10 @@ export function Facet({
)}
{/* A failed fetch shows inline (options may be stale-but-usable below) rather than blanking the facet. */}
{!collapsed && error && !loading && (
- <div className="px-1 pb-1 text-xs text-secondary" data-attr={`logs-facet-${slug}-error`}>
+ <div className="px-1 pb-1 text-xs text-secondary" data-attr={`${dataAttr}-error`}>
{errorMessage}{' '}
{onRetry && (
- <Link onClick={onRetry} data-attr={`logs-facet-${slug}-retry`}>
+ <Link onClick={onRetry} data-attr={`${dataAttr}-retry`}>
Retry
</Link>
)}
@@ -156,9 +173,10 @@ export function Facet({
option={option}
selected={selected.includes(option.value)}
excluded={excluded.includes(option.value)}
- slug={slug}
+ dataAttr={dataAttr}
onToggle={onToggle}
dimZeroCounts={dimZeroCounts}
+ zeroCountReason={zeroCountReason}
/>
))}
</div>
@@ -173,36 +191,40 @@ interface FacetValueRowProps {
options: FacetOption[]
selected: string[]
excluded: string[]
- slug: string
+ dataAttr: string
onToggle: (value: string) => void
dimZeroCounts: boolean
+ zeroCountReason: string
}
function FacetValueRow({
+ ariaAttributes,
index,
style,
options,
selected,
excluded,
- slug,
+ dataAttr,
onToggle,
dimZeroCounts,
+ zeroCountReason,
}: {
- ariaAttributes: Record<string, unknown>
+ ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }
index: number
style: CSSProperties
} & FacetValueRowProps): JSX.Element {
const option = options[index]
return (
// eslint-disable-next-line react/forbid-dom-props
- <div style={style}>
+ <div style={style} {...ariaAttributes}>
<FacetValueButton
option={option}
selected={selected.includes(option.value)}
excluded={excluded.includes(option.value)}
- slug={slug}
+ dataAttr={dataAttr}
onToggle={onToggle}
dimZeroCounts={dimZeroCounts}
+ zeroCountReason={zeroCountReason}
/>
</div>
)
@@ -212,16 +234,18 @@ function FacetValueButton({
option,
selected,
excluded,
- slug,
+ dataAttr,
onToggle,
dimZeroCounts,
+ zeroCountReason,
}: {
option: FacetOption
selected: boolean
excluded: boolean
- slug: string
+ dataAttr: string
onToggle: (value: string) => void
dimZeroCounts: boolean
+ zeroCountReason: string
}): JSX.Element {
// A fixed facet value with no matches in the current scope: dim it, and disable it unless it's
// already active (selected or excluded), so an active-but-now-empty value can still be cycled off.
@@ -236,7 +260,7 @@ function FacetValueButton({
size="small"
fullWidth
className={cn(isZero && 'opacity-50')}
- disabledReason={isZero && !isActive ? 'No matching logs for the current filters' : undefined}
+ disabledReason={isZero && !isActive ? zeroCountReason : undefined}
aria-label={`${option.label}, ${stateLabel}`}
icon={
excluded ? (
@@ -255,11 +279,14 @@ function FacetValueButton({
)
}
onClick={() => onToggle(option.value)}
- data-attr={`logs-facet-${slug}-${option.value}`}
+ data-attr={`${dataAttr}-${slugify(option.value)}`}
>
<span className="flex items-center gap-2 min-w-0 w-full">
{option.color && <span className={cn('w-1 h-3.5 rounded-full shrink-0', option.color)} />}
- <span className={cn('truncate flex-1', excluded && 'line-through text-muted')}>{option.label}</span>
+ {/* Native title so a truncated value is still readable without popover cost per virtualized row. */}
+ <span className={cn('truncate flex-1', excluded && 'line-through text-muted')} title={option.label}>
+ {option.label}
+ </span>
{option.count != null && (
<span className="shrink-0 text-muted tabular-nums">{humanFriendlyLargeNumber(option.count)}</span>
)}
diff --git a/products/tracing/frontend/components/FacetRail/FacetRail.tsx b/frontend/src/lib/components/FacetRail/FacetRail.tsx
similarity index 55%
rename from products/tracing/frontend/components/FacetRail/FacetRail.tsx
rename to frontend/src/lib/components/FacetRail/FacetRail.tsx
index dd04dfce57f8..927f4d1b107c 100644
--- a/products/tracing/frontend/components/FacetRail/FacetRail.tsx
+++ b/frontend/src/lib/components/FacetRail/FacetRail.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { useCallback, useMemo, useRef } from 'react'
+import { Fragment, useMemo, useRef } from 'react'
import { IconPlus } from '@posthog/icons'
import { LemonInput } from '@posthog/lemon-ui'
@@ -9,60 +9,73 @@ import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerL
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TaxonomicStringPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
-import { tracingConfigLogic } from '../../tracingConfigLogic'
-import { customFacetsLogic } from './customFacetsLogic'
-import { facetPresenceLogic } from './facetPresenceLogic'
-import { facetRailLogic } from './facetRailLogic'
-import { facetsByGroup, filterFacetsByName } from './facets'
-import { RailFacet } from './RailFacet'
-
-const ADD_FACET_GROUP_TYPES = [TaxonomicFilterGroupType.SpanAttributes, TaxonomicFilterGroupType.SpanResourceAttributes]
+import { CustomFacetsProduct, customFacetsLogic } from './customFacetsLogic'
+import { FacetGroupItem, facetsByGroup, filterFacetsByName } from './facetGroups'
const DEFAULT_WIDTH_PX = 240
const COLLAPSE_THRESHOLD_PX = 120
-/** Resizable left-hand facet rail, rendered entirely from the FACETS config (see facets.ts). */
-export function FacetRail(): JSX.Element {
+export interface FacetRailProps<T extends FacetGroupItem> {
+ product: CustomFacetsProduct
+ facets: T[]
+ /** Renders one facet. A facet that the name search hides still renders, so its logic stays mounted. */
+ renderFacet: (facet: T, hidden: boolean) => JSX.Element
+ facetNameSearch: string
+ onFacetNameSearchChange: (value: string) => void
+ onCollapsedChange: (collapsed: boolean) => void
+ addFacetGroupTypes: { attribute: TaxonomicFilterGroupType; resourceAttribute: TaxonomicFilterGroupType }
+ /** Persisted width keys. Frozen: a change resets every user's saved rail width. */
+ resizerLogicKey: string
+ resizerPersistPrefix: string
+ /** Prefix for the rail's data-attrs, e.g. `logs-facet-rail`. Frozen: autocapture and tests select on them. */
+ dataAttrPrefix: string
+}
+
+/** Resizable left-hand facet rail: a facet-name search, an add-custom-facet button, and the grouped facets. */
+export function FacetRail<T extends FacetGroupItem>({
+ product,
+ facets,
+ renderFacet,
+ facetNameSearch,
+ onFacetNameSearchChange,
+ onCollapsedChange,
+ addFacetGroupTypes,
+ resizerLogicKey,
+ resizerPersistPrefix,
+ dataAttrPrefix,
+}: FacetRailProps<T>): JSX.Element {
const railRef = useRef<HTMLDivElement>(null)
- const { setFacetRailCollapsed } = useActions(tracingConfigLogic)
- const { visibleFacets } = useValues(facetPresenceLogic)
- const { facetNameSearch } = useValues(facetRailLogic)
- const { setFacetNameSearch } = useActions(facetRailLogic)
- const { addCustomFacet } = useActions(customFacetsLogic)
- const { customFacetsEnabled, entriesLoading } = useValues(customFacetsLogic)
+ const { addCustomFacet } = useActions(customFacetsLogic({ product }))
+ const { customFacetsEnabled, entriesLoading } = useValues(customFacetsLogic({ product }))
- const onToggleClosed = useCallback(
- (shouldBeClosed: boolean) => setFacetRailCollapsed(shouldBeClosed),
- [setFacetRailCollapsed]
- )
const resizerLogicProps: ResizerLogicProps = useMemo(
() => ({
- logicKey: 'tracing-facet-rail',
+ logicKey: resizerLogicKey,
containerRef: railRef,
persistent: true,
- persistPrefix: '2026-07-06',
+ persistPrefix: resizerPersistPrefix,
placement: 'right',
closeThreshold: COLLAPSE_THRESHOLD_PX,
- onToggleClosed,
+ onToggleClosed: onCollapsedChange,
}),
- [onToggleClosed]
+ [resizerLogicKey, resizerPersistPrefix, onCollapsedChange]
)
const { desiredSize } = useValues(resizerLogic(resizerLogicProps))
// Every visible facet renders a container, whether or not the field-name search matches it: a
// non-matching one renders nothing but stays mounted, so clearing the search doesn't refetch.
- const matchingKeys = new Set(filterFacetsByName(visibleFacets, facetNameSearch).map((f) => f.key))
- const groups = facetsByGroup(visibleFacets)
+ const matchingKeys = new Set(filterFacetsByName(facets, facetNameSearch).map((f) => f.key))
+ const groups = facetsByGroup(facets)
return (
<div
ref={railRef}
className="relative flex flex-col shrink-0 border rounded bg-surface-primary overflow-hidden"
- // eslint-disable-next-line react/forbid-dom-props
// The width is the user's alone: a fixed min (not min-content) so a long facet value
// can never force the rail wider — values truncate to fit instead.
+ // eslint-disable-next-line react/forbid-dom-props
style={{ width: desiredSize ?? DEFAULT_WIDTH_PX, minWidth: COLLAPSE_THRESHOLD_PX, maxWidth: '40%' }}
- data-attr="tracing-facet-rail"
+ data-attr={dataAttrPrefix}
>
<div className="flex items-center gap-1 px-2 py-1 border-b">
<LemonInput
@@ -71,25 +84,23 @@ export function FacetRail(): JSX.Element {
fullWidth
placeholder="Search facets…"
value={facetNameSearch}
- onChange={setFacetNameSearch}
- data-attr="tracing-facet-rail-search"
+ onChange={onFacetNameSearchChange}
+ data-attr={`${dataAttrPrefix}-search`}
/>
{customFacetsEnabled && (
<TaxonomicStringPopover
- groupType={TaxonomicFilterGroupType.SpanAttributes}
- groupTypes={ADD_FACET_GROUP_TYPES}
+ groupType={addFacetGroupTypes.attribute}
+ groupTypes={[addFacetGroupTypes.attribute, addFacetGroupTypes.resourceAttribute]}
placeholder={null}
size="small"
icon={<IconPlus />}
tooltip="Add custom facet"
disabledReason={entriesLoading ? 'Custom facets are updating' : undefined}
- data-attr="tracing-facet-rail-add"
+ data-attr={`${dataAttrPrefix}-add`}
onChange={(value, groupType) =>
addCustomFacet(
value,
- groupType === TaxonomicFilterGroupType.SpanResourceAttributes
- ? 'resourceAttribute'
- : 'attribute'
+ groupType === addFacetGroupTypes.resourceAttribute ? 'resourceAttribute' : 'attribute'
)
}
/>
@@ -99,15 +110,15 @@ export function FacetRail(): JSX.Element {
{matchingKeys.size === 0 && facetNameSearch.trim() && (
<div className="px-1 text-xs text-muted">No matching facets</div>
)}
- {groups.map(([group, facets]) => (
+ {groups.map(([group, groupFacets]) => (
<div key={group}>
- {facets.some((facet) => matchingKeys.has(facet.key)) && (
+ {groupFacets.some((facet) => matchingKeys.has(facet.key)) && (
<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((facet) => (
- <RailFacet key={facet.key} facet={facet} hidden={!matchingKeys.has(facet.key)} />
+ {groupFacets.map((facet) => (
+ <Fragment key={facet.key}>{renderFacet(facet, !matchingKeys.has(facet.key))}</Fragment>
))}
</div>
))}
diff --git a/frontend/src/lib/components/FacetRail/customFacetsLogic.test.ts b/frontend/src/lib/components/FacetRail/customFacetsLogic.test.ts
new file mode 100644
index 000000000000..c00dcb12e76c
--- /dev/null
+++ b/frontend/src/lib/components/FacetRail/customFacetsLogic.test.ts
@@ -0,0 +1,170 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ userFacetSettingsPartialUpdate,
+ userFacetSettingsRetrieve,
+} from 'products/platform_features/frontend/generated/api'
+import {
+ UserFacetSettingsEntrySourceTypeEnumApi,
+ UserFacetSettingsRetrieveProduct,
+} from 'products/platform_features/frontend/generated/api.schemas'
+
+import { CustomFacetsProduct, customFacetsLogic } from './customFacetsLogic'
+
+jest.mock('products/platform_features/frontend/generated/api', () => ({
+ __esModule: true,
+ userFacetSettingsRetrieve: jest.fn(),
+ userFacetSettingsPartialUpdate: jest.fn(),
+}))
+
+const mockRetrieve = userFacetSettingsRetrieve as jest.MockedFunction<typeof userFacetSettingsRetrieve>
+const mockPartialUpdate = userFacetSettingsPartialUpdate as jest.MockedFunction<typeof userFacetSettingsPartialUpdate>
+
+const ATTRIBUTE = UserFacetSettingsEntrySourceTypeEnumApi.Attribute
+const RESOURCE_ATTRIBUTE = UserFacetSettingsEntrySourceTypeEnumApi.ResourceAttribute
+
+describe('customFacetsLogic', () => {
+ // Each test sets up its mocks, then mounts fresh via `mount()` below. Mounting inside
+ // `beforeEach` would fire `afterMount` before a test's own mock override took effect, since
+ // re-calling the wrapper mid-test returns the same already-mounted instance.
+ let mounted: ReturnType<typeof customFacetsLogic.build>[] = []
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.clearAllMocks()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
+ mockRetrieve.mockResolvedValue({ custom_facets: [] })
+ mockPartialUpdate.mockImplementation(async (_uuid, _params, body) => ({
+ custom_facets: body?.custom_facets ?? [],
+ }))
+ })
+
+ afterEach(() => {
+ mounted.forEach((logic) => logic.unmount())
+ mounted = []
+ })
+
+ function mount(product: CustomFacetsProduct = 'logs'): ReturnType<typeof customFacetsLogic.build> {
+ const logic = customFacetsLogic({ product })
+ logic.mount()
+ mounted.push(logic)
+ return logic
+ }
+
+ it('does not load or expose custom facets when the feature flag is off', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ const logic = mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockRetrieve).not.toHaveBeenCalled()
+ expect(logic.values.customFacetEntries).toEqual([])
+ })
+
+ it('loads entries when the flag arrives after mount', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ const logic = mount()
+ expect(mockRetrieve).not.toHaveBeenCalled()
+
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
+ await expectLogic(logic).toDispatchActions(['loadEntries', 'loadEntriesSuccess'])
+ })
+
+ it.each(Object.values(UserFacetSettingsRetrieveProduct))(
+ 'mutations for %s build on the persisted list when entries have not loaded yet',
+ async (product) => {
+ // A PATCH replaces the whole server-side list — building it on unloaded local state would
+ // wipe every facet the user pinned elsewhere.
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ mockRetrieve.mockResolvedValue({ custom_facets: [{ key: 'pinned.elsewhere', source_type: ATTRIBUTE }] })
+ const logic = mount(product)
+ logic.actions.addCustomFacet('http.status_code', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(mockRetrieve).toHaveBeenCalledWith('@me', { product })
+ expect(mockPartialUpdate).toHaveBeenCalledWith(
+ '@me',
+ { product },
+ {
+ custom_facets: [
+ { key: 'pinned.elsewhere', source_type: ATTRIBUTE },
+ { key: 'http.status_code', source_type: ATTRIBUTE },
+ ],
+ }
+ )
+ }
+ )
+
+ it('keeps each product on its own list when both rails are mounted', async () => {
+ mockRetrieve.mockImplementation(async (_uuid, { product }) => ({
+ custom_facets: [{ key: `${product}.pinned`, source_type: ATTRIBUTE }],
+ }))
+ const logsLogic = mount('logs')
+ const tracingLogic = mount('tracing')
+ await expectLogic(logsLogic).toDispatchActions(['loadEntriesSuccess'])
+ await expectLogic(tracingLogic).toDispatchActions(['loadEntriesSuccess'])
+
+ tracingLogic.actions.addCustomFacet('http.route', 'attribute')
+ await expectLogic(tracingLogic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(logsLogic.values.customFacetEntries).toEqual([{ key: 'logs.pinned', source_type: ATTRIBUTE }])
+ expect(tracingLogic.values.customFacetEntries).toEqual([
+ { key: 'tracing.pinned', source_type: ATTRIBUTE },
+ { key: 'http.route', source_type: ATTRIBUTE },
+ ])
+ })
+
+ it('loads persisted entries on mount', async () => {
+ mockRetrieve.mockResolvedValue({ custom_facets: [{ key: 'log.iostream', source_type: ATTRIBUTE }] })
+ const logic = mount()
+ await expectLogic(logic).toDispatchActions(['loadEntriesSuccess'])
+
+ expect(logic.values.customFacetEntries).toEqual([{ key: 'log.iostream', source_type: ATTRIBUTE }])
+ })
+
+ it('adding a facet persists the full updated list and updates local state', async () => {
+ const logic = mount()
+ logic.actions.addCustomFacet('log.iostream', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(logic.values.entries).toEqual([{ key: 'log.iostream', source_type: ATTRIBUTE }])
+ expect(mockPartialUpdate).toHaveBeenCalledWith(
+ '@me',
+ { product: 'logs' },
+ { custom_facets: [{ key: 'log.iostream', source_type: ATTRIBUTE }] }
+ )
+ })
+
+ it('adding the same key and sourceType twice does not duplicate or persist again', async () => {
+ const logic = mount()
+ logic.actions.addCustomFacet('log.iostream', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+ mockPartialUpdate.mockClear()
+
+ logic.actions.addCustomFacet('log.iostream', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ expect(logic.values.entries).toHaveLength(1)
+ expect(mockPartialUpdate).not.toHaveBeenCalled()
+ })
+
+ it('removing a facet only drops the matching key+sourceType pair', async () => {
+ // The same key can exist as both an attribute and a resource-attribute facet — removing one
+ // must not also remove the other.
+ const logic = mount()
+ logic.actions.addCustomFacet('environment', 'attribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+ logic.actions.addCustomFacet('environment', 'resourceAttribute')
+ await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
+
+ logic.actions.removeCustomFacet('environment', 'attribute')
+ await expectLogic(logic).toDispatchActions(['removeCustomFacetSuccess'])
+
+ expect(logic.values.entries).toEqual([{ key: 'environment', source_type: RESOURCE_ATTRIBUTE }])
+ })
+})
diff --git a/products/tracing/frontend/components/FacetRail/customFacetsLogic.ts b/frontend/src/lib/components/FacetRail/customFacetsLogic.ts
similarity index 70%
rename from products/tracing/frontend/components/FacetRail/customFacetsLogic.ts
rename to frontend/src/lib/components/FacetRail/customFacetsLogic.ts
index 20a95db72d63..434d5f8ea2d7 100644
--- a/products/tracing/frontend/components/FacetRail/customFacetsLogic.ts
+++ b/frontend/src/lib/components/FacetRail/customFacetsLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -8,16 +8,24 @@ import {
userFacetSettingsPartialUpdate,
userFacetSettingsRetrieve,
} from 'products/platform_features/frontend/generated/api'
-import { UserFacetSettingsEntryApi } from 'products/platform_features/frontend/generated/api.schemas'
+import {
+ UserFacetSettingsEntryApi,
+ UserFacetSettingsEntrySourceTypeEnumApi,
+ UserFacetSettingsRetrieveProduct,
+} from 'products/platform_features/frontend/generated/api.schemas'
-import { CustomFacetSourceType, FacetConfig, buildCustomFacet } from './facets'
+export type CustomFacetsProduct = UserFacetSettingsRetrieveProduct
+/** A custom facet's source kind, as persisted per-user — mirrors the backend's `source_type` choices. */
+export type CustomFacetSourceType = UserFacetSettingsEntrySourceTypeEnumApi
-const PRODUCT = 'tracing' as const
+export interface CustomFacetsLogicProps {
+ product: CustomFacetsProduct
+}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface customFacetsLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
- customFacets: FacetConfig[]
+ customFacetEntries: UserFacetSettingsEntryApi[]
customFacetsEnabled: boolean
entries: UserFacetSettingsEntryApi[]
entriesLoaded: boolean
@@ -31,7 +39,7 @@ export interface customFacetsLogicActions {
sourceType: CustomFacetSourceType
) => {
key: string
- sourceType: CustomFacetSourceType
+ sourceType: UserFacetSettingsEntrySourceTypeEnumApi
}
addCustomFacetFailure: (
error: string,
@@ -44,13 +52,13 @@ export interface customFacetsLogicActions {
entries: UserFacetSettingsEntryApi[],
payload?: {
key: string
- sourceType: CustomFacetSourceType
+ sourceType: UserFacetSettingsEntrySourceTypeEnumApi
}
) => {
entries: UserFacetSettingsEntryApi[]
payload?: {
key: string
- sourceType: CustomFacetSourceType
+ sourceType: UserFacetSettingsEntrySourceTypeEnumApi
}
}
loadEntries: () => {
@@ -79,7 +87,7 @@ export interface customFacetsLogicActions {
sourceType: CustomFacetSourceType
) => {
key: string
- sourceType: CustomFacetSourceType
+ sourceType: UserFacetSettingsEntrySourceTypeEnumApi
}
removeCustomFacetFailure: (
error: string,
@@ -92,39 +100,45 @@ export interface customFacetsLogicActions {
entries: UserFacetSettingsEntryApi[],
payload?: {
key: string
- sourceType: CustomFacetSourceType
+ sourceType: UserFacetSettingsEntrySourceTypeEnumApi
}
) => {
entries: UserFacetSettingsEntryApi[]
payload?: {
key: string
- sourceType: CustomFacetSourceType
+ sourceType: UserFacetSettingsEntrySourceTypeEnumApi
}
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface customFacetsLogicMeta {
+ key: UserFacetSettingsRetrieveProduct
__keaTypeGenInternalSelectorTypes: {
customFacetsEnabled: (featureFlags: FeatureFlagsSet) => boolean
- customFacets: (entries: UserFacetSettingsEntryApi[], customFacetsEnabled: boolean) => FacetConfig[]
+ customFacetEntries: (
+ entries: UserFacetSettingsEntryApi[],
+ customFacetsEnabled: boolean
+ ) => UserFacetSettingsEntryApi[]
}
}
export type customFacetsLogicType = MakeLogicType<
customFacetsLogicValues,
customFacetsLogicActions,
- Record<string, any>,
+ CustomFacetsLogicProps,
customFacetsLogicMeta
>
/**
- * The user's custom facets for tracing, persisted server-side (per user, per team) so they follow
- * the user across devices. A singleton (not keyed by viewer id): the underlying setting is one row
- * per user/team/product, not one per rail instance.
+ * The user's custom facets for one product's facet rail, persisted server-side (per user, per team)
+ * so they follow the user across devices. Keyed by product, not by viewer id: the underlying setting
+ * is one row per user/team/product, not one per rail instance.
*/
export const customFacetsLogic = kea<customFacetsLogicType>([
- path(['products', 'tracing', 'frontend', 'components', 'FacetRail', 'customFacetsLogic']),
+ props({} as CustomFacetsLogicProps),
+ key((props) => props.product),
+ path((key) => ['lib', 'components', 'FacetRail', 'customFacetsLogic', key]),
connect(() => ({ values: [featureFlagLogic, ['featureFlags']] })),
@@ -134,20 +148,19 @@ export const customFacetsLogic = kea<customFacetsLogicType>([
removeCustomFacet: (key: string, sourceType: CustomFacetSourceType) => ({ key, sourceType }),
}),
- loaders(({ values }) => {
+ loaders(({ props, values }) => {
+ const params = { product: props.product }
// The PATCH replaces the whole server-side list, so a mutation must build on the persisted
// entries: local state can be empty when the load failed or never ran, and using it as the
// base would wipe the user's saved facets.
const baseEntries = async (): Promise<UserFacetSettingsEntryApi[]> =>
- values.entriesLoaded
- ? values.entries
- : (await userFacetSettingsRetrieve('@me', { product: PRODUCT })).custom_facets
+ values.entriesLoaded ? values.entries : (await userFacetSettingsRetrieve('@me', params)).custom_facets
return {
entries: [
[] as UserFacetSettingsEntryApi[],
{
loadEntries: async () => {
- const response = await userFacetSettingsRetrieve('@me', { product: PRODUCT })
+ const response = await userFacetSettingsRetrieve('@me', params)
return response.custom_facets
},
addCustomFacet: async ({ key, sourceType }) => {
@@ -156,11 +169,7 @@ export const customFacetsLogic = kea<customFacetsLogicType>([
return base
}
const nextEntries = [...base, { key, source_type: sourceType }]
- await userFacetSettingsPartialUpdate(
- '@me',
- { product: PRODUCT },
- { custom_facets: nextEntries }
- )
+ await userFacetSettingsPartialUpdate('@me', params, { custom_facets: nextEntries })
return nextEntries
},
removeCustomFacet: async ({ key, sourceType }) => {
@@ -168,11 +177,7 @@ export const customFacetsLogic = kea<customFacetsLogicType>([
const nextEntries = base.filter(
(entry) => !(entry.key === key && entry.source_type === sourceType)
)
- await userFacetSettingsPartialUpdate(
- '@me',
- { product: PRODUCT },
- { custom_facets: nextEntries }
- )
+ await userFacetSettingsPartialUpdate('@me', params, { custom_facets: nextEntries })
return nextEntries
},
},
@@ -196,10 +201,11 @@ export const customFacetsLogic = kea<customFacetsLogicType>([
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.CUSTOM_FACET_PINNING],
],
- customFacets: [
+ // Each product turns these into its own facet configs, since the filter a facet writes is product-specific.
+ customFacetEntries: [
(s) => [s.entries, s.customFacetsEnabled],
- (entries: UserFacetSettingsEntryApi[], customFacetsEnabled: boolean): FacetConfig[] =>
- customFacetsEnabled ? entries.map((entry) => buildCustomFacet(entry.key, entry.source_type)) : [],
+ (entries: UserFacetSettingsEntryApi[], customFacetsEnabled: boolean): UserFacetSettingsEntryApi[] =>
+ customFacetsEnabled ? entries : [],
],
}),
diff --git a/frontend/src/lib/components/FacetRail/facetGroups.test.ts b/frontend/src/lib/components/FacetRail/facetGroups.test.ts
new file mode 100644
index 000000000000..88cdc5b129d0
--- /dev/null
+++ b/frontend/src/lib/components/FacetRail/facetGroups.test.ts
@@ -0,0 +1,28 @@
+import { FacetGroupItem, filterFacetsByName } from './facetGroups'
+
+const facet = (key: string, title: string, group: string): FacetGroupItem => ({ key, title, group })
+
+const FACETS: FacetGroupItem[] = [
+ facet('level', 'Level', 'Standard'),
+ facet('service', 'Service', 'Standard'),
+ facet('namespace', 'Namespace', 'Kubernetes'),
+ facet('pod', 'Pod', 'Kubernetes'),
+ facet('host', 'Host', 'Infrastructure'),
+]
+
+describe('facetGroups', () => {
+ describe('filterFacetsByName', () => {
+ it.each([
+ ['blank query returns all', '', ['level', 'service', 'namespace', 'pod', 'host']],
+ ['whitespace-only returns all', ' ', ['level', 'service', 'namespace', 'pod', 'host']],
+ ['matches a field title', 'namespace', ['namespace']],
+ ['title match is case-insensitive', 'NAMESPACE', ['namespace']],
+ ['partial title match', 'serv', ['service']],
+ ['matches a whole group by name', 'kubernetes', ['namespace', 'pod']],
+ ['group match is case-insensitive', 'INFRA', ['host']],
+ ['no match returns empty', 'zzz', []],
+ ])('%s', (_, query, expectedKeys) => {
+ expect(filterFacetsByName(FACETS, query).map((f) => f.key)).toEqual(expectedKeys)
+ })
+ })
+})
diff --git a/frontend/src/lib/components/FacetRail/facetGroups.ts b/frontend/src/lib/components/FacetRail/facetGroups.ts
new file mode 100644
index 000000000000..d0abb6c5df34
--- /dev/null
+++ b/frontend/src/lib/components/FacetRail/facetGroups.ts
@@ -0,0 +1,35 @@
+/** The fields the shared rail needs from a product's facet config to search and group it. */
+export interface FacetGroupItem {
+ key: string
+ title: string
+ group: string
+}
+
+/**
+ * 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<T extends FacetGroupItem>(facets: T[], query: string): T[] {
+ const needle = query.trim().toLowerCase()
+ if (!needle) {
+ return facets
+ }
+ return facets.filter(
+ (facet) => facet.title.toLowerCase().includes(needle) || facet.group.toLowerCase().includes(needle)
+ )
+}
+
+/** Group facets by `group`, preserving first-appearance order of both groups and facets. */
+export function facetsByGroup<T extends FacetGroupItem>(facets: T[]): [string, T[]][] {
+ const groups: [string, T[]][] = []
+ 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
+}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
deleted file mode 100644
index 2530cdfff84a..000000000000
--- a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { useCallback, useMemo, useRef } from 'react'
-
-import { IconPlus } from '@posthog/icons'
-import { LemonInput } from '@posthog/lemon-ui'
-
-import { Resizer } from 'lib/components/Resizer/Resizer'
-import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { TaxonomicStringPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
-
-import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
-
-import { customFacetsLogic } from './customFacetsLogic'
-import { facetPresenceLogic } from './facetPresenceLogic'
-import { facetRailLogic } from './facetRailLogic'
-import { facetsByGroup, filterFacetsByName } from './facets'
-import { RailFacet } from './RailFacet'
-
-const DEFAULT_WIDTH_PX = 240
-const COLLAPSE_THRESHOLD_PX = 120
-const ADD_FACET_GROUP_TYPES = [TaxonomicFilterGroupType.LogAttributes, TaxonomicFilterGroupType.LogResourceAttributes]
-
-export interface FacetRailProps {
- id: string
-}
-
-/** Resizable left-hand facet rail, rendered entirely from the FACETS config (see facets.ts). */
-export function FacetRail({ id }: FacetRailProps): JSX.Element {
- const railRef = useRef<HTMLDivElement>(null)
- const { setFacetRailCollapsed } = useActions(logsViewerConfigLogic)
- const { visibleFacets } = useValues(facetPresenceLogic({ id }))
- const { facetNameSearch } = useValues(facetRailLogic({ id }))
- const { setFacetNameSearch } = useActions(facetRailLogic({ id }))
- const { addCustomFacet } = useActions(customFacetsLogic)
- const { customFacetsEnabled, entriesLoading } = useValues(customFacetsLogic)
-
- const onToggleClosed = useCallback(
- (shouldBeClosed: boolean) => setFacetRailCollapsed(shouldBeClosed),
- [setFacetRailCollapsed]
- )
- const resizerLogicProps: ResizerLogicProps = useMemo(
- () => ({
- logicKey: `logs-facet-rail-${id}`,
- containerRef: railRef,
- persistent: true,
- persistPrefix: '2026-06-18',
- placement: 'right',
- closeThreshold: COLLAPSE_THRESHOLD_PX,
- onToggleClosed,
- }),
- [id, onToggleClosed]
- )
- const { desiredSize } = useValues(resizerLogic(resizerLogicProps))
-
- // Every visible facet renders a container, whether or not the field-name search matches it: a
- // non-matching one renders nothing but stays mounted, so clearing the search doesn't refetch.
- const matchingKeys = new Set(filterFacetsByName(visibleFacets, facetNameSearch).map((f) => f.key))
- const groups = facetsByGroup(visibleFacets)
-
- return (
- <div
- ref={railRef}
- className="relative flex flex-col shrink-0 border rounded bg-surface-primary overflow-hidden"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ width: desiredSize ?? DEFAULT_WIDTH_PX, minWidth: 'min-content', maxWidth: '40%' }}
- data-attr="logs-facet-rail"
- >
- <div className="flex items-center gap-1 px-2 py-1 border-b">
- <LemonInput
- type="search"
- size="small"
- fullWidth
- placeholder="Search facets…"
- value={facetNameSearch}
- onChange={setFacetNameSearch}
- data-attr="logs-facet-rail-search"
- />
- {customFacetsEnabled && (
- <TaxonomicStringPopover
- groupType={TaxonomicFilterGroupType.LogAttributes}
- groupTypes={ADD_FACET_GROUP_TYPES}
- placeholder={null}
- size="small"
- icon={<IconPlus />}
- tooltip="Add custom facet"
- disabledReason={entriesLoading ? 'Custom facets are updating' : undefined}
- data-attr="logs-facet-rail-add"
- onChange={(value, groupType) =>
- addCustomFacet(
- value,
- groupType === TaxonomicFilterGroupType.LogResourceAttributes
- ? 'resourceAttribute'
- : 'attribute'
- )
- }
- />
- )}
- </div>
- <div className="flex-1 min-h-0 overflow-y-auto p-2">
- {matchingKeys.size === 0 && facetNameSearch.trim() && (
- <div className="px-1 text-xs text-muted">No matching facets</div>
- )}
- {groups.map(([group, facets]) => (
- <div key={group}>
- {facets.some((facet) => matchingKeys.has(facet.key)) && (
- <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((facet) => (
- <RailFacet key={facet.key} id={id} facet={facet} hidden={!matchingKeys.has(facet.key)} />
- ))}
- </div>
- ))}
- </div>
- <Resizer {...resizerLogicProps} visible={false} offset="0.25rem" handleClassName="rounded my-1" />
- </div>
- )
-}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/LogsFacetRail.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/LogsFacetRail.tsx
new file mode 100644
index 000000000000..90b24b54df63
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/LogsFacetRail.tsx
@@ -0,0 +1,42 @@
+import { useActions, useValues } from 'kea'
+
+import { FacetRail } from 'lib/components/FacetRail/FacetRail'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
+
+import { facetPresenceLogic } from './facetPresenceLogic'
+import { facetRailLogic } from './facetRailLogic'
+import { RailFacet } from './RailFacet'
+
+const ADD_FACET_GROUP_TYPES = {
+ attribute: TaxonomicFilterGroupType.LogAttributes,
+ resourceAttribute: TaxonomicFilterGroupType.LogResourceAttributes,
+}
+
+export interface LogsFacetRailProps {
+ id: string
+}
+
+/** The logs viewer's facet rail, rendered entirely from the FACETS config (see facets.ts). */
+export function LogsFacetRail({ id }: LogsFacetRailProps): JSX.Element {
+ const { setFacetRailCollapsed } = useActions(logsViewerConfigLogic)
+ const { visibleFacets } = useValues(facetPresenceLogic({ id }))
+ const { facetNameSearch } = useValues(facetRailLogic({ id }))
+ const { setFacetNameSearch } = useActions(facetRailLogic({ id }))
+
+ return (
+ <FacetRail
+ product="logs"
+ facets={visibleFacets}
+ renderFacet={(facet, hidden) => <RailFacet id={id} facet={facet} hidden={hidden} />}
+ facetNameSearch={facetNameSearch}
+ onFacetNameSearchChange={setFacetNameSearch}
+ onCollapsedChange={setFacetRailCollapsed}
+ addFacetGroupTypes={ADD_FACET_GROUP_TYPES}
+ resizerLogicKey={`logs-facet-rail-${id}`}
+ resizerPersistPrefix="2026-06-18"
+ dataAttrPrefix="logs-facet-rail"
+ />
+ )
+}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
index 80f3b75e9213..38c0ee9f646d 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
@@ -1,10 +1,11 @@
import { useActions, useValues } from 'kea'
import { useCallback, useMemo } from 'react'
+import { customFacetsLogic } from 'lib/components/FacetRail/customFacetsLogic'
+import { Facet, FacetOption } from 'lib/components/FacetRail/Facet'
+
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
-import { customFacetsLogic } from './customFacetsLogic'
-import { Facet, FacetOption } from './Facet'
import { facetFilterTarget, facetSelection } from './facetFilters'
import { facetRailLogic } from './facetRailLogic'
import { FacetConfig, customFacetIdentity, mergeSelectedIntoOptions } from './facets'
@@ -30,8 +31,8 @@ export function RailFacet({ id, facet, hidden }: RailFacetProps): JSX.Element |
const { setFacetSearch, retryFacetValues } = useActions(facetValuesLogic(logicProps))
const { filterGroup } = useValues(logsViewerFiltersLogic({ id }))
const { toggleFacetValue, toggleFacetCollapsed } = useActions(facetRailLogic({ id }))
- const { removeCustomFacet } = useActions(customFacetsLogic)
- const { entriesLoading } = useValues(customFacetsLogic)
+ const { removeCustomFacet } = useActions(customFacetsLogic({ product: 'logs' }))
+ const { entriesLoading } = useValues(customFacetsLogic({ product: 'logs' }))
const removeDisabledReason = entriesLoading ? 'Custom facets are updating' : undefined
const { source } = facet
@@ -87,6 +88,8 @@ export function RailFacet({ id, facet, hidden }: RailFacetProps): JSX.Element |
selected={selected}
excluded={excluded}
onToggle={onToggle}
+ dataAttrPrefix="logs-facet"
+ zeroCountReason="No matching logs for the current filters"
loading={facetValuesLoading}
collapsed={collapsed}
onToggleCollapsed={onToggleCollapsed}
@@ -106,6 +109,8 @@ export function RailFacet({ id, facet, hidden }: RailFacetProps): JSX.Element |
selected={selected}
excluded={excluded}
onToggle={onToggle}
+ dataAttrPrefix="logs-facet"
+ zeroCountReason="No matching logs for the current filters"
loading={facetValuesLoading}
emptyLabel={facet.emptyLabel}
searchValue={facet.searchable ? facetSearch : undefined}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.test.ts
deleted file mode 100644
index bce44fd5e692..000000000000
--- a/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.test.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-
-import { initKeaTests } from '~/test/init'
-
-import {
- userFacetSettingsPartialUpdate,
- userFacetSettingsRetrieve,
-} from 'products/platform_features/frontend/generated/api'
-import { UserFacetSettingsEntrySourceTypeEnumApi } from 'products/platform_features/frontend/generated/api.schemas'
-
-import { customFacetsLogic } from './customFacetsLogic'
-
-jest.mock('products/platform_features/frontend/generated/api', () => ({
- __esModule: true,
- userFacetSettingsRetrieve: jest.fn(),
- userFacetSettingsPartialUpdate: jest.fn(),
-}))
-
-const mockRetrieve = userFacetSettingsRetrieve as jest.MockedFunction<typeof userFacetSettingsRetrieve>
-const mockPartialUpdate = userFacetSettingsPartialUpdate as jest.MockedFunction<typeof userFacetSettingsPartialUpdate>
-
-describe('customFacetsLogic', () => {
- // A singleton logic (no `key`) — each test sets up its mocks, then mounts fresh via `mount()`
- // below. Mounting inside `beforeEach` would fire `afterMount` before a test's own mock override
- // took effect, since re-calling the wrapper mid-test returns the same already-mounted instance.
- let logic: ReturnType<typeof customFacetsLogic.build>
-
- beforeEach(() => {
- initKeaTests()
- jest.clearAllMocks()
- featureFlagLogic.mount()
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
- mockRetrieve.mockResolvedValue({ custom_facets: [] })
- mockPartialUpdate.mockImplementation(async (_uuid, _params, body) => ({
- custom_facets: body?.custom_facets ?? [],
- }))
- })
-
- afterEach(() => {
- logic?.unmount()
- })
-
- function mount(): ReturnType<typeof customFacetsLogic.build> {
- logic = customFacetsLogic()
- logic.mount()
- return logic
- }
-
- it('does not load or expose custom facets when the feature flag is off', async () => {
- featureFlagLogic.actions.setFeatureFlags([], {})
- mount()
- await expectLogic(logic).toFinishAllListeners()
-
- expect(mockRetrieve).not.toHaveBeenCalled()
- expect(logic.values.customFacets).toEqual([])
- })
-
- it('loads entries when the flag arrives after mount', async () => {
- featureFlagLogic.actions.setFeatureFlags([], {})
- mount()
- expect(mockRetrieve).not.toHaveBeenCalled()
-
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
- await expectLogic(logic).toDispatchActions(['loadEntries', 'loadEntriesSuccess'])
- })
-
- it('mutations build on the persisted list when entries have not loaded yet', async () => {
- // A PATCH replaces the whole server-side list — building it on unloaded local state would
- // wipe every facet the user pinned elsewhere.
- featureFlagLogic.actions.setFeatureFlags([], {})
- mockRetrieve.mockResolvedValue({
- custom_facets: [
- { key: 'pinned.elsewhere', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- ],
- })
- mount()
- logic.actions.addCustomFacet('log.iostream', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
-
- expect(mockPartialUpdate).toHaveBeenCalledWith(
- '@me',
- { product: 'logs' },
- {
- custom_facets: [
- { key: 'pinned.elsewhere', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- { key: 'log.iostream', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- ],
- }
- )
- })
-
- it('loads persisted entries on mount and exposes them as facet configs', async () => {
- mockRetrieve.mockResolvedValue({
- custom_facets: [{ key: 'log.iostream', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute }],
- })
- mount()
- await expectLogic(logic).toDispatchActions(['loadEntriesSuccess'])
-
- expect(logic.values.customFacets).toEqual([
- expect.objectContaining({
- key: 'custom:attribute:log.iostream',
- source: { type: 'attribute', key: 'log.iostream' },
- }),
- ])
- })
-
- it('adding a facet persists the full updated list and updates local state', async () => {
- mount()
- logic.actions.addCustomFacet('log.iostream', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
-
- expect(logic.values.entries).toEqual([
- { key: 'log.iostream', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- ])
- expect(mockPartialUpdate).toHaveBeenCalledWith(
- '@me',
- { product: 'logs' },
- { custom_facets: [{ key: 'log.iostream', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute }] }
- )
- })
-
- it('adding the same key and sourceType twice does not duplicate or persist again', async () => {
- mount()
- logic.actions.addCustomFacet('log.iostream', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
- mockPartialUpdate.mockClear()
-
- logic.actions.addCustomFacet('log.iostream', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
-
- expect(logic.values.entries).toHaveLength(1)
- expect(mockPartialUpdate).not.toHaveBeenCalled()
- })
-
- it('removing a facet only drops the matching key+sourceType pair', async () => {
- // The same key can exist as both an attribute and a resource-attribute facet — removing one
- // must not also remove the other.
- mount()
- logic.actions.addCustomFacet('environment', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
- logic.actions.addCustomFacet('environment', 'resourceAttribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
-
- logic.actions.removeCustomFacet('environment', 'attribute')
- await expectLogic(logic).toDispatchActions(['removeCustomFacetSuccess'])
-
- expect(logic.values.entries).toEqual([
- { key: 'environment', source_type: UserFacetSettingsEntrySourceTypeEnumApi.ResourceAttribute },
- ])
- })
-})
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.ts
deleted file mode 100644
index 7be2e72e92e7..000000000000
--- a/products/logs/frontend/components/LogsViewer/FacetRail/customFacetsLogic.ts
+++ /dev/null
@@ -1,223 +0,0 @@
-import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
-
-import {
- userFacetSettingsPartialUpdate,
- userFacetSettingsRetrieve,
-} from 'products/platform_features/frontend/generated/api'
-import { UserFacetSettingsEntryApi } from 'products/platform_features/frontend/generated/api.schemas'
-
-import { CustomFacetSourceType, FacetConfig, buildCustomFacet } from './facets'
-
-const PRODUCT = 'logs' as const
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface customFacetsLogicValues {
- featureFlags: FeatureFlagsSet // featureFlagLogic
- customFacets: FacetConfig[]
- customFacetsEnabled: boolean
- entries: UserFacetSettingsEntryApi[]
- entriesLoaded: boolean
- entriesLoading: boolean
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface customFacetsLogicActions {
- addCustomFacet: (
- key: string,
- sourceType: CustomFacetSourceType
- ) => {
- key: string
- sourceType: CustomFacetSourceType
- }
- addCustomFacetFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- addCustomFacetSuccess: (
- entries: UserFacetSettingsEntryApi[],
- payload?: {
- key: string
- sourceType: CustomFacetSourceType
- }
- ) => {
- entries: UserFacetSettingsEntryApi[]
- payload?: {
- key: string
- sourceType: CustomFacetSourceType
- }
- }
- loadEntries: () => {
- value: true
- }
- loadEntriesFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadEntriesSuccess: (
- entries: UserFacetSettingsEntryApi[],
- payload?: {
- value: true
- }
- ) => {
- entries: UserFacetSettingsEntryApi[]
- payload?: {
- value: true
- }
- }
- removeCustomFacet: (
- key: string,
- sourceType: CustomFacetSourceType
- ) => {
- key: string
- sourceType: CustomFacetSourceType
- }
- removeCustomFacetFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- removeCustomFacetSuccess: (
- entries: UserFacetSettingsEntryApi[],
- payload?: {
- key: string
- sourceType: CustomFacetSourceType
- }
- ) => {
- entries: UserFacetSettingsEntryApi[]
- payload?: {
- key: string
- sourceType: CustomFacetSourceType
- }
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface customFacetsLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- customFacetsEnabled: (featureFlags: FeatureFlagsSet) => boolean
- customFacets: (entries: UserFacetSettingsEntryApi[], customFacetsEnabled: boolean) => FacetConfig[]
- }
-}
-
-export type customFacetsLogicType = MakeLogicType<
- customFacetsLogicValues,
- customFacetsLogicActions,
- Record<string, any>,
- customFacetsLogicMeta
->
-
-/**
- * The user's custom facets for logs, persisted server-side (per user, per team) so they follow the
- * user across devices. A singleton (not keyed by viewer id): the underlying setting is one row per
- * user/team/product, not one per rail instance.
- */
-export const customFacetsLogic = kea<customFacetsLogicType>([
- path(['products', 'logs', 'frontend', 'components', 'LogsViewer', 'FacetRail', 'customFacetsLogic']),
-
- connect(() => ({ values: [featureFlagLogic, ['featureFlags']] })),
-
- actions({
- loadEntries: true,
- addCustomFacet: (key: string, sourceType: CustomFacetSourceType) => ({ key, sourceType }),
- removeCustomFacet: (key: string, sourceType: CustomFacetSourceType) => ({ key, sourceType }),
- }),
-
- loaders(({ values }) => {
- // The PATCH replaces the whole server-side list, so a mutation must build on the persisted
- // entries: local state can be empty when the load failed or never ran, and using it as the
- // base would wipe the user's saved facets.
- const baseEntries = async (): Promise<UserFacetSettingsEntryApi[]> =>
- values.entriesLoaded
- ? values.entries
- : (await userFacetSettingsRetrieve('@me', { product: PRODUCT })).custom_facets
- return {
- entries: [
- [] as UserFacetSettingsEntryApi[],
- {
- loadEntries: async () => {
- const response = await userFacetSettingsRetrieve('@me', { product: PRODUCT })
- return response.custom_facets
- },
- addCustomFacet: async ({ key, sourceType }) => {
- const base = await baseEntries()
- if (base.some((entry) => entry.key === key && entry.source_type === sourceType)) {
- return base
- }
- const nextEntries = [...base, { key, source_type: sourceType }]
- await userFacetSettingsPartialUpdate(
- '@me',
- { product: PRODUCT },
- { custom_facets: nextEntries }
- )
- return nextEntries
- },
- removeCustomFacet: async ({ key, sourceType }) => {
- const base = await baseEntries()
- const nextEntries = base.filter(
- (entry) => !(entry.key === key && entry.source_type === sourceType)
- )
- await userFacetSettingsPartialUpdate(
- '@me',
- { product: PRODUCT },
- { custom_facets: nextEntries }
- )
- return nextEntries
- },
- },
- ],
- }
- }),
-
- reducers({
- entriesLoaded: [
- false,
- {
- loadEntriesSuccess: () => true,
- },
- ],
- }),
-
- selectors({
- // A primitive, so downstream facet identities only change when the gate actually flips —
- // the featureFlags object gets a fresh identity on every flag refresh.
- customFacetsEnabled: [
- (s) => [s.featureFlags],
- (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.CUSTOM_FACET_PINNING],
- ],
- customFacets: [
- (s) => [s.entries, s.customFacetsEnabled],
- (entries: UserFacetSettingsEntryApi[], customFacetsEnabled: boolean): FacetConfig[] =>
- customFacetsEnabled ? entries.map((entry) => buildCustomFacet(entry.key, entry.source_type)) : [],
- ],
- }),
-
- listeners(({ actions, values }) => ({
- // Flags resolve asynchronously and often land after this logic mounts — without this, a
- // flagged user's pinned facets would stay unloaded for the whole session.
- [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
- if (values.customFacetsEnabled && !values.entriesLoaded && !values.entriesLoading) {
- actions.loadEntries()
- }
- },
- })),
-
- events(({ actions, values }) => ({
- afterMount: () => {
- if (values.customFacetsEnabled) {
- actions.loadEntries()
- }
- },
- })),
-])
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts
index bbe1fc6e2d10..116a501a28c4 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts
@@ -2,13 +2,14 @@ import { MakeLogicType, connect, events, kea, key, listeners, path, props, selec
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
+import { customFacetsLogic } from 'lib/components/FacetRail/customFacetsLogic'
import { teamLogic } from 'scenes/teamLogic'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
+import { UserFacetSettingsEntryApi } from 'products/platform_features/frontend/generated/api.schemas'
import { logsAttributesRetrieve } from '../../../generated/api'
-import { customFacetsLogic } from './customFacetsLogic'
-import { FACETS, FacetConfig, presenceProbeKeys, presenceProbeWindow, resolveFacets } from './facets'
+import { FACETS, FacetConfig, buildCustomFacet, presenceProbeKeys, presenceProbeWindow, resolveFacets } from './facets'
// Request the exact keys used by curated facets. Other resource keys cannot hide a facet.
// Send date_from and date_to as separate parameters. The generated client converts objects to strings.
@@ -21,13 +22,14 @@ export interface FacetPresenceLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetPresenceLogicValues {
- customFacets: FacetConfig[] // customFacetsLogic
+ customFacetEntries: UserFacetSettingsEntryApi[] // customFacetsLogic
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
explicitDate: boolean | null | undefined
} // logsViewerFiltersLogic
currentTeamId: number | null // teamLogic
+ customFacets: FacetConfig[]
presenceWindow: {
date_from: string
date_to?: string | undefined
@@ -80,6 +82,7 @@ export interface facetPresenceLogicMeta {
} | null
) => string
resolvedFacets: (presentResourceKeys: string[]) => FacetConfig[]
+ customFacets: (customFacetEntries: UserFacetSettingsEntryApi[]) => FacetConfig[]
visibleFacets: (resolvedFacets: FacetConfig[], customFacets: FacetConfig[]) => FacetConfig[]
}
}
@@ -106,8 +109,8 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([
values: [
teamLogic,
['currentTeamId'],
- customFacetsLogic,
- ['customFacets'],
+ customFacetsLogic({ product: 'logs' }),
+ ['customFacetEntries'],
logsViewerFiltersLogic({ id: props.id }),
['utcDateRange'],
],
@@ -164,6 +167,11 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([
(s) => [s.presentResourceKeys],
(presentResourceKeys: string[]): FacetConfig[] => resolveFacets(FACETS, presentResourceKeys),
],
+ customFacets: [
+ (s) => [s.customFacetEntries],
+ (customFacetEntries: UserFacetSettingsEntryApi[]): FacetConfig[] =>
+ customFacetEntries.map((entry) => buildCustomFacet(entry.key, entry.source_type)),
+ ],
visibleFacets: [
(s) => [s.resolvedFacets, s.customFacets],
(resolvedFacets: FacetConfig[], customFacets: FacetConfig[]): FacetConfig[] => [
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
index 5c9635ff4727..8015184a64c7 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
@@ -1,6 +1,7 @@
+import { FacetOption } from 'lib/components/FacetRail/Facet'
+
import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
-import { FacetOption } from './Facet'
import {
FACETS as CONFIGURED_FACETS,
FacetConfig,
@@ -8,45 +9,13 @@ import {
buildCustomFacet,
customFacetIdentity,
facetScopeSignature,
- filterFacetsByName,
mergeSelectedIntoOptions,
presenceProbeKeys,
presenceProbeWindow,
resolveFacets,
} from './facets'
-const facet = (key: string, title: string, group: string): FacetConfig => ({
- key,
- title,
- group,
- kind: 'dynamic',
- source: { type: 'resourceAttribute', key },
-})
-
-const FACETS: FacetConfig[] = [
- facet('level', 'Level', 'Standard'),
- facet('service', 'Service', 'Standard'),
- facet('namespace', 'Namespace', 'Kubernetes'),
- facet('pod', 'Pod', 'Kubernetes'),
- facet('host', 'Host', 'Infrastructure'),
-]
-
describe('facets', () => {
- describe('filterFacetsByName', () => {
- it.each([
- ['blank query returns all', '', ['level', 'service', 'namespace', 'pod', 'host']],
- ['whitespace-only returns all', ' ', ['level', 'service', 'namespace', 'pod', 'host']],
- ['matches a field title', 'namespace', ['namespace']],
- ['title match is case-insensitive', 'NAMESPACE', ['namespace']],
- ['partial title match', 'serv', ['service']],
- ['matches a whole group by name', 'kubernetes', ['namespace', 'pod']],
- ['group match is case-insensitive', 'INFRA', ['host']],
- ['no match returns empty', 'zzz', []],
- ])('%s', (_, query, expectedKeys) => {
- expect(filterFacetsByName(FACETS, query).map((f) => f.key)).toEqual(expectedKeys)
- })
- })
-
describe('mergeSelectedIntoOptions', () => {
const fetched: FacetOption[] = [
{ value: 'api', label: 'api', count: 10 },
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
index abed2e1626a3..0cb901ce6e1f 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
@@ -1,3 +1,5 @@
+import { CustomFacetSourceType } from 'lib/components/FacetRail/customFacetsLogic'
+import { FacetOption } from 'lib/components/FacetRail/Facet'
import { dayjs } from 'lib/dayjs'
import { dateStringToDayJs } from 'lib/utils/dateFilters'
@@ -5,7 +7,6 @@ import { UniversalFiltersGroup } from '~/types'
import { SEVERITY_BAR_COLORS } from 'products/logs/frontend/components/VirtualizedLogsList/columnDefinitions'
-import { FacetOption } from './Facet'
import {
SERVICE_NAME_FILTER,
SEVERITY_LEVEL_FILTER,
@@ -283,21 +284,6 @@ export function resolveFacets(facets: FacetConfig[], presentResourceKeys: string
return resolved
}
-/**
- * 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 (included or excluded) value of a dynamic facet renders even when absent
* from the fetched list —
@@ -318,23 +304,6 @@ export function mergeSelectedIntoOptions(fetched: FacetOption[], selected: strin
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
-}
-
-/** A custom facet's source kind, as persisted per-user — mirrors the backend's `source_type` choices. */
-export type CustomFacetSourceType = 'attribute' | 'resourceAttribute'
-
/** Builds a rail-renderable FacetConfig for a user-added custom facet — always dynamic, with a remove control. */
export function buildCustomFacet(key: string, sourceType: CustomFacetSourceType): FacetConfig {
return {
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
index c9a0cc6d45f8..623f73b175a9 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
@@ -14,7 +14,7 @@ import { LogsPatterns } from 'products/logs/frontend/components/LogsPatterns/Log
import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
import { LogsViewerFilters, LogsViewerScope } from 'products/logs/frontend/components/LogsViewer/config/types'
import { logsViewerDataLogic } from 'products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic'
-import { FacetRail } from 'products/logs/frontend/components/LogsViewer/FacetRail/FacetRail'
+import { LogsFacetRail } from 'products/logs/frontend/components/LogsViewer/FacetRail/LogsFacetRail'
import { LogsQueryBar } from 'products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsQueryBar'
import { logsFilterHistoryLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsFilterHistoryLogic'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
@@ -428,7 +428,7 @@ function LogsViewerContent({
/>
{sparklineSection}
<div className="flex flex-row gap-2 flex-1 min-h-0">
- {!facetRailCollapsed && <FacetRail id={id} />}
+ {!facetRailCollapsed && <LogsFacetRail id={id} />}
<div className="flex flex-col gap-2 flex-1 min-w-0">
{resultsColumn(<LogsDisplayBar {...displayBarProps} showFacetRailToggle />)}
</div>
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index 8abaaa814f6c..624c4041eeb6 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -25,7 +25,7 @@ import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-genera
import { QueryFailedOverlay } from 'products/logs/frontend/components/QueryFailedOverlay'
import { ComparisonBar } from './components/Comparison/ComparisonBar'
-import { FacetRail } from './components/FacetRail/FacetRail'
+import { TracingFacetRail } from './components/FacetRail/TracingFacetRail'
import { TraceDrawer } from './components/TraceDrawer/TraceDrawer'
import { TracingSqlEditor } from './components/TracingSqlEditor/TracingSqlEditor'
import { VirtualizedSpanList } from './components/VirtualizedSpanList/VirtualizedSpanList'
@@ -309,7 +309,7 @@ function TracingSceneContents(): JSX.Element {
}
/>
<div className="flex flex-row gap-2 flex-1 min-h-0">
- {facetRailEnabled && !facetRailCollapsed && <FacetRail />}
+ {facetRailEnabled && !facetRailCollapsed && <TracingFacetRail />}
<div className="flex flex-col gap-2 flex-1 min-w-0 min-h-0">
<TracingDisplayBar />
{compareActive && (!operationsViewEnabled || activeTracingTab !== 'operations') && (
diff --git a/products/tracing/frontend/components/FacetRail/Facet.tsx b/products/tracing/frontend/components/FacetRail/Facet.tsx
deleted file mode 100644
index 16796b699d00..000000000000
--- a/products/tracing/frontend/components/FacetRail/Facet.tsx
+++ /dev/null
@@ -1,267 +0,0 @@
-import { CSSProperties, useMemo } from 'react'
-import { List } from 'react-window'
-
-import { IconChevronDown, IconChevronRight, IconMinusSmall, IconWarning, IconX } from '@posthog/icons'
-import { LemonButton, LemonCheckbox, LemonInput, Link, Tooltip } from '@posthog/lemon-ui'
-
-import { cn } from 'lib/utils/css-classes'
-import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
-
-import { FacetOption } from './facets'
-
-const ROW_HEIGHT = 33
-
-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
- /** When provided, renders a search box above the values (state owned by the caller). */
- searchValue?: string
- onSearchChange?: (value: string) => void
- searchPlaceholder?: string
- collapsed?: boolean
- onToggleCollapsed?: () => void
- /** When set, values render in a fixed-height virtualized list capped at this many pixels. */
- maxHeight?: number
- /** For fixed facets: render zero-count values dimmed, and disabled unless already selected. */
- dimZeroCounts?: boolean
- /** The facet's latest fetch failed — show an inline error instead of pretending the list is fresh (suppresses emptyLabel). */
- error?: boolean
- /** Renders a Retry link next to the error message. */
- onRetry?: () => void
- /** When set, renders a remove control in the header — for user-added custom facets only. */
- onRemove?: () => void
- /** Disables the remove control (with this explanation) while a custom-facet update is in flight. */
- removeDisabledReason?: string
-}
-
-/**
- * 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,
- excluded = [],
- onToggle,
- loading = false,
- emptyLabel = 'No values',
- searchValue,
- onSearchChange,
- searchPlaceholder = 'Search…',
- collapsed = false,
- onToggleCollapsed,
- maxHeight,
- dimZeroCounts = false,
- error = false,
- onRetry,
- onRemove,
- removeDisabledReason,
-}: FacetProps): JSX.Element {
- const slug = slugify(title)
- const errorMessage = options.length > 0 ? "Couldn't refresh values." : "Couldn't load values."
-
- const rowProps = useMemo<FacetValueRowProps>(
- () => ({ options, selected, excluded, slug, onToggle, dimZeroCounts }),
- [options, selected, excluded, slug, onToggle, dimZeroCounts]
- )
-
- return (
- <div className="mb-3">
- <div className="flex items-center gap-1 w-full px-1 mb-1">
- <button
- type="button"
- onClick={onToggleCollapsed}
- disabled={!onToggleCollapsed}
- className="flex items-center gap-1 flex-1 min-w-0 text-[10px] font-semibold uppercase tracking-wide text-secondary hover:text-default"
- data-attr={`tracing-facet-${slug}-header`}
- >
- {collapsed ? <IconChevronRight /> : <IconChevronDown />}
- <span className="truncate">{title}</span>
- {error && !loading && (
- <Tooltip title={collapsed ? `${errorMessage} Expand to retry.` : errorMessage}>
- <IconWarning className="shrink-0 text-xs text-danger" />
- </Tooltip>
- )}
- </button>
- {onRemove && (
- <LemonButton
- size="small"
- icon={<IconX />}
- onClick={onRemove}
- disabledReason={removeDisabledReason}
- tooltip="Remove custom facet"
- data-attr={`tracing-facet-${slug}-remove`}
- />
- )}
- </div>
- {!collapsed && onSearchChange && (
- <div className="px-1 pb-1">
- <LemonInput
- type="search"
- size="small"
- fullWidth
- placeholder={searchPlaceholder}
- value={searchValue ?? ''}
- onChange={onSearchChange}
- />
- </div>
- )}
- {/* A failed fetch shows inline (options may be stale-but-usable below) rather than blanking the facet. */}
- {!collapsed && error && !loading && (
- <div className="px-1 pb-1 text-xs text-secondary" data-attr={`tracing-facet-${slug}-error`}>
- {errorMessage}{' '}
- {onRetry && (
- <Link onClick={onRetry} data-attr={`tracing-facet-${slug}-retry`}>
- Retry
- </Link>
- )}
- </div>
- )}
- {!collapsed &&
- (loading && options.length === 0 ? (
- <div className="px-1 text-xs text-muted">Loading…</div>
- ) : options.length === 0 ? (
- // The error line above already explains the missing values — don't add "No values".
- !error && <div className="px-1 text-xs text-muted">{emptyLabel}</div>
- ) : (
- // Dim the list while a refetch is in flight (e.g. typing in search) so there's
- // feedback that results are updating, rather than the list silently changing.
- <div className={cn(loading && 'opacity-60 transition-opacity')}>
- {maxHeight ? (
- <List<FacetValueRowProps>
- // eslint-disable-next-line react/forbid-dom-props
- style={{ width: '100%', height: Math.min(options.length * ROW_HEIGHT, maxHeight) }}
- rowCount={options.length}
- rowHeight={ROW_HEIGHT}
- overscanCount={5}
- rowComponent={FacetValueRow}
- rowProps={rowProps}
- />
- ) : (
- <div className="space-y-px">
- {options.map((option) => (
- <FacetValueButton
- key={option.value}
- option={option}
- selected={selected.includes(option.value)}
- excluded={excluded.includes(option.value)}
- slug={slug}
- onToggle={onToggle}
- dimZeroCounts={dimZeroCounts}
- />
- ))}
- </div>
- )}
- </div>
- ))}
- </div>
- )
-}
-
-interface FacetValueRowProps {
- options: FacetOption[]
- selected: string[]
- excluded: string[]
- slug: string
- onToggle: (value: string) => void
- dimZeroCounts: boolean
-}
-
-function FacetValueRow({
- ariaAttributes,
- index,
- style,
- options,
- selected,
- excluded,
- slug,
- onToggle,
- dimZeroCounts,
-}: {
- ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }
- index: number
- style: CSSProperties
-} & FacetValueRowProps): JSX.Element {
- const option = options[index]
- return (
- // eslint-disable-next-line react/forbid-dom-props
- <div style={style} {...ariaAttributes}>
- <FacetValueButton
- option={option}
- selected={selected.includes(option.value)}
- excluded={excluded.includes(option.value)}
- slug={slug}
- onToggle={onToggle}
- dimZeroCounts={dimZeroCounts}
- />
- </div>
- )
-}
-
-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 or excluded (so an active-but-now-empty value can still be cycled off).
- const isZero = dimZeroCounts && option.count === 0
- return (
- <LemonButton
- type="tertiary"
- size="small"
- fullWidth
- className={cn(isZero && 'opacity-50')}
- 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={cn('truncate flex-1', excluded && 'line-through text-muted')} title={option.label}>
- {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/RailFacet.tsx b/products/tracing/frontend/components/FacetRail/RailFacet.tsx
index 5825504ee698..bcfb7c0c2fb5 100644
--- a/products/tracing/frontend/components/FacetRail/RailFacet.tsx
+++ b/products/tracing/frontend/components/FacetRail/RailFacet.tsx
@@ -1,19 +1,13 @@
import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
+import { customFacetsLogic } from 'lib/components/FacetRail/customFacetsLogic'
+import { Facet, FacetOption } from 'lib/components/FacetRail/Facet'
+
import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from 'products/tracing/frontend/tracingFiltersLogic'
-import { customFacetsLogic } from './customFacetsLogic'
-import { Facet } from './Facet'
import { facetRailLogic } from './facetRailLogic'
-import {
- FacetConfig,
- FacetOption,
- customFacetIdentity,
- facetSelection,
- facetValueGroup,
- mergeSelectedIntoOptions,
-} from './facets'
+import { FacetConfig, customFacetIdentity, facetSelection, facetValueGroup, mergeSelectedIntoOptions } from './facets'
import { facetValuesLogic } from './facetValuesLogic'
export interface RailFacetProps {
@@ -36,8 +30,8 @@ export function RailFacet({ facet, id = TRACING_SCENE_VIEWER_ID, hidden }: RailF
const { setFacetSearch, retryFacetValues } = useActions(facetValuesLogic(logicProps))
const { serviceNames, filters } = useValues(tracingFiltersLogic({ id }))
const { toggleFacetValue, toggleFacetCollapsed } = useActions(facetRailLogic({ id }))
- const { removeCustomFacet } = useActions(customFacetsLogic)
- const { entriesLoading } = useValues(customFacetsLogic)
+ const { removeCustomFacet } = useActions(customFacetsLogic({ product: 'tracing' }))
+ const { entriesLoading } = useValues(customFacetsLogic({ product: 'tracing' }))
const removeDisabledReason = entriesLoading ? 'Custom facets are updating' : undefined
if (hidden) {
@@ -74,6 +68,8 @@ export function RailFacet({ facet, id = TRACING_SCENE_VIEWER_ID, hidden }: RailF
selected={selected}
excluded={excluded}
onToggle={onToggle}
+ dataAttrPrefix="tracing-facet"
+ zeroCountReason="No matching spans for the current filters"
loading={facetValuesLoading}
collapsed={collapsed}
onToggleCollapsed={onToggleCollapsed}
@@ -96,6 +92,8 @@ export function RailFacet({ facet, id = TRACING_SCENE_VIEWER_ID, hidden }: RailF
selected={selected}
excluded={excluded}
onToggle={onToggle}
+ dataAttrPrefix="tracing-facet"
+ zeroCountReason="No matching spans for the current filters"
loading={facetValuesLoading}
emptyLabel={facet.emptyLabel}
searchValue={search}
diff --git a/products/tracing/frontend/components/FacetRail/TracingFacetRail.tsx b/products/tracing/frontend/components/FacetRail/TracingFacetRail.tsx
new file mode 100644
index 000000000000..e1367eef7870
--- /dev/null
+++ b/products/tracing/frontend/components/FacetRail/TracingFacetRail.tsx
@@ -0,0 +1,37 @@
+import { useActions, useValues } from 'kea'
+
+import { FacetRail } from 'lib/components/FacetRail/FacetRail'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { tracingConfigLogic } from '../../tracingConfigLogic'
+import { facetPresenceLogic } from './facetPresenceLogic'
+import { facetRailLogic } from './facetRailLogic'
+import { RailFacet } from './RailFacet'
+
+const ADD_FACET_GROUP_TYPES = {
+ attribute: TaxonomicFilterGroupType.SpanAttributes,
+ resourceAttribute: TaxonomicFilterGroupType.SpanResourceAttributes,
+}
+
+/** The tracing scene's facet rail, rendered entirely from the FACETS config (see facets.ts). */
+export function TracingFacetRail(): JSX.Element {
+ const { setFacetRailCollapsed } = useActions(tracingConfigLogic)
+ const { visibleFacets } = useValues(facetPresenceLogic)
+ const { facetNameSearch } = useValues(facetRailLogic)
+ const { setFacetNameSearch } = useActions(facetRailLogic)
+
+ return (
+ <FacetRail
+ product="tracing"
+ facets={visibleFacets}
+ renderFacet={(facet, hidden) => <RailFacet facet={facet} hidden={hidden} />}
+ facetNameSearch={facetNameSearch}
+ onFacetNameSearchChange={setFacetNameSearch}
+ onCollapsedChange={setFacetRailCollapsed}
+ addFacetGroupTypes={ADD_FACET_GROUP_TYPES}
+ resizerLogicKey="tracing-facet-rail"
+ resizerPersistPrefix="2026-07-06"
+ dataAttrPrefix="tracing-facet-rail"
+ />
+ )
+}
diff --git a/products/tracing/frontend/components/FacetRail/customFacetsLogic.test.ts b/products/tracing/frontend/components/FacetRail/customFacetsLogic.test.ts
deleted file mode 100644
index a19db93891d7..000000000000
--- a/products/tracing/frontend/components/FacetRail/customFacetsLogic.test.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-
-import { initKeaTests } from '~/test/init'
-
-import {
- userFacetSettingsPartialUpdate,
- userFacetSettingsRetrieve,
-} from 'products/platform_features/frontend/generated/api'
-import { UserFacetSettingsEntrySourceTypeEnumApi } from 'products/platform_features/frontend/generated/api.schemas'
-
-import { customFacetsLogic } from './customFacetsLogic'
-
-jest.mock('products/platform_features/frontend/generated/api', () => ({
- __esModule: true,
- userFacetSettingsRetrieve: jest.fn(),
- userFacetSettingsPartialUpdate: jest.fn(),
-}))
-
-const mockRetrieve = userFacetSettingsRetrieve as jest.MockedFunction<typeof userFacetSettingsRetrieve>
-const mockPartialUpdate = userFacetSettingsPartialUpdate as jest.MockedFunction<typeof userFacetSettingsPartialUpdate>
-
-describe('customFacetsLogic', () => {
- // A singleton logic (no `key`) — each test sets up its mocks, then mounts fresh via `mount()`
- // below. Mounting inside `beforeEach` would fire `afterMount` before a test's own mock override
- // took effect, since re-calling the wrapper mid-test returns the same already-mounted instance.
- let logic: ReturnType<typeof customFacetsLogic.build>
-
- beforeEach(() => {
- initKeaTests()
- jest.clearAllMocks()
- featureFlagLogic.mount()
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
- mockRetrieve.mockResolvedValue({ custom_facets: [] })
- mockPartialUpdate.mockImplementation(async (_uuid, _params, body) => ({
- custom_facets: body?.custom_facets ?? [],
- }))
- })
-
- afterEach(() => {
- logic?.unmount()
- })
-
- function mount(): ReturnType<typeof customFacetsLogic.build> {
- logic = customFacetsLogic()
- logic.mount()
- return logic
- }
-
- it('does not load or expose custom facets when the feature flag is off', async () => {
- featureFlagLogic.actions.setFeatureFlags([], {})
- mount()
- await expectLogic(logic).toFinishAllListeners()
-
- expect(mockRetrieve).not.toHaveBeenCalled()
- expect(logic.values.customFacets).toEqual([])
- })
-
- it('loads entries when the flag arrives after mount', async () => {
- featureFlagLogic.actions.setFeatureFlags([], {})
- mount()
- expect(mockRetrieve).not.toHaveBeenCalled()
-
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOM_FACET_PINNING]: true })
- await expectLogic(logic).toDispatchActions(['loadEntries', 'loadEntriesSuccess'])
- })
-
- it('mutations build on the persisted list when entries have not loaded yet', async () => {
- // A PATCH replaces the whole server-side list — building it on unloaded local state would
- // wipe every facet the user pinned elsewhere.
- featureFlagLogic.actions.setFeatureFlags([], {})
- mockRetrieve.mockResolvedValue({
- custom_facets: [
- { key: 'pinned.elsewhere', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- ],
- })
- mount()
- logic.actions.addCustomFacet('http.status_code', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
-
- expect(mockPartialUpdate).toHaveBeenCalledWith(
- '@me',
- { product: 'tracing' },
- {
- custom_facets: [
- { key: 'pinned.elsewhere', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- { key: 'http.status_code', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- ],
- }
- )
- })
-
- it('loads persisted entries on mount and exposes them as facet configs', async () => {
- mockRetrieve.mockResolvedValue({
- custom_facets: [
- { key: 'http.status_code', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- ],
- })
- mount()
- await expectLogic(logic).toDispatchActions(['loadEntriesSuccess'])
-
- expect(logic.values.customFacets).toEqual([
- expect.objectContaining({
- key: 'custom:attribute:http.status_code',
- source: { type: 'attribute', key: 'http.status_code' },
- }),
- ])
- })
-
- it('adding a facet persists the full updated list and updates local state', async () => {
- mount()
- logic.actions.addCustomFacet('http.status_code', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
-
- expect(logic.values.entries).toEqual([
- { key: 'http.status_code', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- ])
- expect(mockPartialUpdate).toHaveBeenCalledWith(
- '@me',
- { product: 'tracing' },
- {
- custom_facets: [
- { key: 'http.status_code', source_type: UserFacetSettingsEntrySourceTypeEnumApi.Attribute },
- ],
- }
- )
- })
-
- it('adding the same key and sourceType twice does not duplicate or persist again', async () => {
- mount()
- logic.actions.addCustomFacet('http.status_code', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
- mockPartialUpdate.mockClear()
-
- logic.actions.addCustomFacet('http.status_code', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
-
- expect(logic.values.entries).toHaveLength(1)
- expect(mockPartialUpdate).not.toHaveBeenCalled()
- })
-
- it('removing a facet only drops the matching key+sourceType pair', async () => {
- // The same key can exist as both an attribute and a resource-attribute facet — removing one
- // must not also remove the other.
- mount()
- logic.actions.addCustomFacet('environment', 'attribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
- logic.actions.addCustomFacet('environment', 'resourceAttribute')
- await expectLogic(logic).toDispatchActions(['addCustomFacetSuccess'])
-
- logic.actions.removeCustomFacet('environment', 'attribute')
- await expectLogic(logic).toDispatchActions(['removeCustomFacetSuccess'])
-
- expect(logic.values.entries).toEqual([
- { key: 'environment', source_type: UserFacetSettingsEntrySourceTypeEnumApi.ResourceAttribute },
- ])
- })
-})
diff --git a/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts b/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts
index 2f5909141495..229c39ccf97b 100644
--- a/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts
+++ b/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts
@@ -1,14 +1,15 @@
import { MakeLogicType, connect, events, kea, key, path, props, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { customFacetsLogic } from 'lib/components/FacetRail/customFacetsLogic'
import { teamLogic } from 'scenes/teamLogic'
+import { UserFacetSettingsEntryApi } from 'products/platform_features/frontend/generated/api.schemas'
import { TRACING_SCENE_VIEWER_ID } from 'products/tracing/frontend/tracingFiltersLogic'
import { tracingSpansAttributesRetrieve } from '../../generated/api'
import { TracingSpansAttributesRetrieveAttributeType } from '../../generated/api.schemas'
-import { customFacetsLogic } from './customFacetsLogic'
-import { FACETS, FacetConfig, resolveFacets } from './facets'
+import { FACETS, FacetConfig, buildCustomFacet, resolveFacets } from './facets'
export interface FacetPresenceLogicProps {
id: string
@@ -16,8 +17,9 @@ export interface FacetPresenceLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetPresenceLogicValues {
- customFacets: FacetConfig[] // customFacetsLogic
+ customFacetEntries: UserFacetSettingsEntryApi[] // customFacetsLogic
currentTeamId: number | null // teamLogic
+ customFacets: FacetConfig[]
presentResourceKeys: string[]
presentResourceKeysLoading: boolean
resolvedFacets: FacetConfig[]
@@ -48,6 +50,7 @@ export interface facetPresenceLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
resolvedFacets: (presentResourceKeys: string[]) => FacetConfig[]
+ customFacets: (customFacetEntries: UserFacetSettingsEntryApi[]) => FacetConfig[]
visibleFacets: (resolvedFacets: FacetConfig[], customFacets: FacetConfig[]) => FacetConfig[]
}
}
@@ -71,7 +74,7 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([
path((key) => ['products', 'tracing', 'frontend', 'components', 'FacetRail', 'facetPresenceLogic', key]),
connect(() => ({
- values: [teamLogic, ['currentTeamId'], customFacetsLogic, ['customFacets']],
+ values: [teamLogic, ['currentTeamId'], customFacetsLogic({ product: 'tracing' }), ['customFacetEntries']],
})),
loaders(({ values }) => ({
@@ -105,6 +108,11 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([
(s) => [s.presentResourceKeys],
(presentResourceKeys: string[]): FacetConfig[] => resolveFacets(FACETS, presentResourceKeys),
],
+ customFacets: [
+ (s) => [s.customFacetEntries],
+ (customFacetEntries: UserFacetSettingsEntryApi[]): FacetConfig[] =>
+ customFacetEntries.map((entry) => buildCustomFacet(entry.key, entry.source_type)),
+ ],
visibleFacets: [
(s) => [s.resolvedFacets, s.customFacets],
(resolvedFacets: FacetConfig[], customFacets: FacetConfig[]): FacetConfig[] => [
diff --git a/products/tracing/frontend/components/FacetRail/facets.ts b/products/tracing/frontend/components/FacetRail/facets.ts
index 5abad4cdc523..0f14e948d361 100644
--- a/products/tracing/frontend/components/FacetRail/facets.ts
+++ b/products/tracing/frontend/components/FacetRail/facets.ts
@@ -1,3 +1,6 @@
+import { CustomFacetSourceType } from 'lib/components/FacetRail/customFacetsLogic'
+import { FacetOption } from 'lib/components/FacetRail/Facet'
+
import {
FilterLogicalOperator,
PropertyFilterType,
@@ -6,13 +9,6 @@ import {
UniversalFiltersGroup,
} from '~/types'
-/** One selectable row in a facet: a value with its span count. */
-export interface FacetOption {
- value: string
- label: string
- count: number
-}
-
/**
* Whether a facet's value set is known ahead of time or discovered from the data.
*
@@ -430,21 +426,6 @@ export function resolveFacets(facets: FacetConfig[], presentResourceKeys: string
return resolved
}
-/**
- * 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
@@ -468,23 +449,6 @@ export function mergeSelectedIntoOptions(fetched: FacetOption[], selected: strin
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
-}
-
-/** A custom facet's source kind, as persisted per-user — mirrors the backend's `source_type` choices. */
-export type CustomFacetSourceType = 'attribute' | 'resourceAttribute'
-
/** Builds a rail-renderable FacetConfig for a user-added custom facet — always dynamic, with a remove control. */
export function buildCustomFacet(key: string, sourceType: CustomFacetSourceType): FacetConfig {
return {