Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add's a filter bar component to design system (#35238)

Saxon Fletcher98ae279a2bcd
diff --git a/apps/design-system/__registry__/index.tsx b/apps/design-system/__registry__/index.tsx
index d4554da3efa..71d36ee0000 100644
--- a/apps/design-system/__registry__/index.tsx
+++ b/apps/design-system/__registry__/index.tsx
@@ -720,6 +720,17 @@ export const Index: Record<string, any> = {
subcategory: "undefined",
chunks: []
},
+ "filter-bar-demo": {
+ name: "filter-bar-demo",
+ type: "components:example",
+ registryDependencies: ["filter-bar"],
+ component: React.lazy(() => import("@/registry/default/example/filter-bar-demo")),
+ source: "",
+ files: ["registry/default/example/filter-bar-demo.tsx"],
+ category: "undefined",
+ subcategory: "undefined",
+ chunks: []
+ },
"hover-card-demo": {
name: "hover-card-demo",
type: "components:example",
diff --git a/apps/design-system/config/docs.ts b/apps/design-system/config/docs.ts
index 1031738338e..e3bda291b96 100644
--- a/apps/design-system/config/docs.ts
+++ b/apps/design-system/config/docs.ts
@@ -117,6 +117,11 @@ export const docsConfig: DocsConfig = {
href: '/docs/fragments/multi-select',
items: [],
},
+ {
+ title: 'Filter Bar',
+ href: '/docs/fragments/filter-bar',
+ items: [],
+ },
{
title: 'Logs Bar Chart',
href: '/docs/fragments/logs-bar-chart',
diff --git a/apps/design-system/content/docs/fragments/filter-bar.mdx b/apps/design-system/content/docs/fragments/filter-bar.mdx
new file mode 100644
index 00000000000..fed27c7219d
--- /dev/null
+++ b/apps/design-system/content/docs/fragments/filter-bar.mdx
@@ -0,0 +1,214 @@
+---
+title: Filter Bar
+description: An advanced filtering component with support for multiple conditions and operators.
+component: true
+fragment: true
+---
+
+<ComponentPreview
+ name="filter-bar-demo"
+ description="An advanced filtering component with support for multiple conditions and operators."
+ peekCode
+ showDottedGrid
+ wide
+/>
+
+## Usage
+
+The Filter Bar component provides advanced filtering capabilities with support for multiple conditions, operators, and different field types. It can be used with both static and async options.
+
+```tsx
+const filterProperties = [
+ {
+ label: 'Name',
+ name: 'name',
+ type: 'string',
+ operators: ['=', '!=', 'CONTAINS', 'STARTS WITH', 'ENDS WITH'],
+ },
+ {
+ label: 'Status',
+ name: 'status',
+ type: 'string',
+ options: ['active', 'inactive', 'pending'],
+ operators: ['=', '!='],
+ },
+]
+
+export function FilterDemo() {
+ const [filters, setFilters] = useState<FilterGroup>(initialFilters)
+ const [freeformText, setFreeformText] = useState('')
+
+ return (
+ <FilterBar
+ filterProperties={filterProperties}
+ freeformText={freeformText}
+ onFreeformTextChange={setFreeformText}
+ filters={filters}
+ onFilterChange={setFilters}
+ />
+ )
+}
+```
+
+## API Reference
+
+### FilterProperty
+
+```tsx
+interface FilterProperty {
+ label: string
+ name: string
+ type: 'string' | 'number' | 'date' | 'boolean'
+ operators: string[]
+ options?: string[] | ((search?: string) => Promise<string[]> | string[])
+}
+```
+
+### FilterGroup
+
+```tsx
+interface FilterGroup {
+ logicalOperator: 'AND' | 'OR'
+ conditions: (FilterCondition | FilterGroup)[]
+}
+```
+
+### FilterCondition
+
+```tsx
+interface FilterCondition {
+ propertyName: string
+ value: string | number | boolean | Date
+ operator: string
+}
+```
+
+### Component Props
+
+| Prop | Type | Description |
+| -------------------- | ------------------------------ | ---------------------------------------- |
+| filterProperties | FilterProperty[] | Array of properties that can be filtered |
+| filters | FilterGroup | Current filter state |
+| onFilterChange | (filters: FilterGroup) => void | Callback when filters change |
+| freeformText | string | Current free-form search text |
+| onFreeformTextChange | (text: string) => void | Callback when free-form text changes |
+| aiApiUrl | string? | Optional URL for AI-powered filtering |
+
+## AI Integration
+
+The Filter Bar component supports AI-powered filtering through an optional API endpoint. When `aiApiUrl` is provided, the component will send natural language queries to be converted into structured filters.
+
+### API Endpoint
+
+The AI API endpoint should accept POST requests with the following structure:
+
+```typescript
+// Request body
+interface AIFilterRequest {
+ prompt: string // Natural language query
+ filterProperties: FilterProperty[] // Available filter properties
+}
+
+// Response body
+interface AIFilterResponse {
+ logicalOperator: 'AND' | 'OR'
+ conditions: (FilterCondition | FilterGroup)[]
+}
+```
+
+### Example API Implementation
+
+```typescript
+import { generateObject } from 'ai'
+import { openai } from '@ai-sdk/openai'
+import { z } from 'zod'
+
+// Define schemas for validation
+const FilterProperty = z.object({
+ label: z.string(),
+ name: z.string(),
+ type: z.enum(['string', 'number', 'date', 'boolean']),
+ options: z.array(z.string()).optional(),
+ operators: z.array(z.string()).optional(),
+})
+
+const FilterCondition = z.object({
+ propertyName: z.string(),
+ value: z.union([z.string(), z.number(), z.boolean(), z.null()]),
+ operator: z.string(),
+})
+
+type FilterGroupType = {
+ logicalOperator: 'AND' | 'OR'
+ conditions: Array<z.infer<typeof FilterCondition> | FilterGroupType>
+}
+
+const FilterGroup: z.ZodType<FilterGroupType> = z.lazy(() =>
+ z.object({
+ logicalOperator: z.enum(['AND', 'OR']),
+ conditions: z.array(z.union([FilterCondition, FilterGroup])),
+ })
+)
+
+export async function POST(req: Request) {
+ const { prompt, filterProperties } = await req.json()
+ const filterPropertiesString = JSON.stringify(filterProperties)
+
+ try {
+ const { object } = await generateObject({
+ model: openai('gpt-4-mini'),
+ schema: FilterGroup,
+ prompt: `Generate a filter group based on the following prompt: "${prompt}".
+ Use only these filter properties: ${filterPropertiesString}.
+ Each property has its own set of valid operators defined in the operators field.
+ Return a filter group with a logical operator ('AND'/'OR') and an array of conditions.
+ Each condition can be either a filter condition or another filter group.
+ Filter conditions should have the structure: { propertyName: string, value: string | number | boolean | null, operator: string }.
+ Ensure that the generated filters use only the provided property names and their corresponding operators.`,
+ })
+
+ // Validate that all propertyNames exist in filterProperties
+ const validatePropertyNames = (group: FilterGroupType): boolean => {
+ return group.conditions.every((condition) => {
+ if ('logicalOperator' in condition) {
+ return validatePropertyNames(condition as FilterGroupType)
+ }
+ const property = filterProperties.find(
+ (p: z.infer<typeof FilterProperty>) => p.name === condition.propertyName
+ )
+ if (!property) return false
+ // Validate operator is valid for this property
+ return property.operators?.includes(condition.operator) ?? false
+ })
+ }
+
+ if (!validatePropertyNames(object)) {
+ throw new Error('Invalid property names or operators in generated filter')
+ }
+
+ // Zod will throw an error if the object doesn't match the schema
+ const validatedFilters = FilterGroup.parse(object)
+ return Response.json(validatedFilters)
+ } catch (error: any) {
+ console.error('Error in AI filtering:', error)
+ return Response.json({ error: error.message || 'AI filtering failed' }, { status: 500 })
+ }
+}
+```
+
+### Usage with AI
+
+```tsx
+export function FilterDemoWithAI() {
+ const [filters, setFilters] = useState<FilterGroup>(initialFilters)
+
+ return (
+ <FilterBar
+ filterProperties={filterProperties}
+ filters={filters}
+ onFilterChange={setFilters}
+ aiApiUrl="/api/filter-ai" // Enable AI filtering
+ />
+ )
+}
+```
diff --git a/apps/design-system/public/llms.txt b/apps/design-system/public/llms.txt
index 6d50fe9e7f0..34725799b8c 100644
--- a/apps/design-system/public/llms.txt
+++ b/apps/design-system/public/llms.txt
@@ -1,5 +1,5 @@
# Supabase Design System
-Last updated: 2025-03-05T12:59:50.911Z
+Last updated: 2025-04-24T06:00:07.374Z
## Overview
The Design System used in Supabase Studio.
@@ -130,6 +130,8 @@ The Design System used in Supabase Studio.
- Displays a callout for user attention.
- [Assistant Chat](https://supabase-design-system.vercel.app/design-system/docs/fragments/assistant-chat)
- Bespoke Assistant chat text area, with support for a commands Popover.
+- [Filter Bar](https://supabase-design-system.vercel.app/design-system/docs/fragments/filter-bar)
+ - An advanced filtering component with support for multiple conditions and operators.
- [Form Item Layout](https://supabase-design-system.vercel.app/design-system/docs/fragments/form-item-layout)
- A helper component that provides a layout for form items.
- [Info Tooltip](https://supabase-design-system.vercel.app/design-system/docs/fragments/info-tooltip)
@@ -144,6 +146,8 @@ The Design System used in Supabase Studio.
- Multiple selection component.
- [Text Confirm Dialog](https://supabase-design-system.vercel.app/design-system/docs/fragments/text-confirm-dialog)
- A modal dialog that interrupts the user with important content and expects a response.
+- [Table of Contents (TOC)](https://supabase-design-system.vercel.app/design-system/docs/fragments/toc)
+ - List of page anchors for the current page.
- [Icons](https://supabase-design-system.vercel.app/design-system/docs/icons)
- Icons system breakdown. Copy values of Icons.
- [Introduction](https://supabase-design-system.vercel.app/design-system/docs/index)
diff --git a/apps/design-system/registry/default/example/filter-bar-demo.tsx b/apps/design-system/registry/default/example/filter-bar-demo.tsx
new file mode 100644
index 00000000000..06ccabdc71e
--- /dev/null
+++ b/apps/design-system/registry/default/example/filter-bar-demo.tsx
@@ -0,0 +1,166 @@
+import { format } from 'date-fns'
+import { useState } from 'react'
+import { Button, Button_Shadcn_, Calendar, Input_Shadcn_ } from 'ui'
+import { CustomOptionProps, FilterBar, FilterGroup } from 'ui-patterns'
+
+function CustomDatePicker({ onChange, onCancel, search }: CustomOptionProps) {
+ const [date, setDate] = useState<any | undefined>(
+ search
+ ? {
+ from: new Date(search),
+ to: undefined,
+ }
+ : undefined
+ )
+
+ return (
+ <div className="w-full space-y-4">
+ <Calendar
+ initialFocus
+ mode="range"
+ defaultMonth={date?.from}
+ selected={date}
+ onSelect={setDate}
+ className="w-full"
+ />
+ <div className="flex justify-end gap-2 py-3 px-4 border-t">
+ <Button type="default" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button
+ type="primary"
+ onClick={() =>
+ onChange(
+ date?.from
+ ? date.to
+ ? `${format(date.from, 'yyyy-MM-dd')} - ${format(date.to, 'yyyy-MM-dd')}`
+ : format(date.from, 'yyyy-MM-dd')
+ : ''
+ )
+ }
+ >
+ Apply
+ </Button>
+ </div>
+ </div>
+ )
+}
+
+function CustomTimePicker({ onChange, onCancel, search }: CustomOptionProps) {
+ const [time, setTime] = useState(search || '')
+
+ return (
+ <div className="space-y-4">
+ <h3 className="text-lg font-medium">Select Time</h3>
+ <Input_Shadcn_ type="time" value={time} onChange={(e) => setTime(e.target.value)} />
+ <div className="flex justify-end gap-2">
+ <Button_Shadcn_ variant="outline" onClick={onCancel}>
+ Cancel
+ </Button_Shadcn_>
+ <Button_Shadcn_ onClick={() => onChange(time)}>Apply</Button_Shadcn_>
+ </div>
+ </div>
+ )
+}
+
+function CustomRangePicker({ onChange, onCancel, search }: CustomOptionProps) {
+ const [range, setRange] = useState(search || '')
+
+ return (
+ <div className="space-y-4">
+ <h3 className="text-lg font-medium">Select Range</h3>
+ <Input_Shadcn_ type="range" value={range} onChange={(e) => setRange(e.target.value)} />
+ <div className="flex justify-end gap-2">
+ <Button_Shadcn_ variant="outline" onClick={onCancel}>
+ Cancel
+ </Button_Shadcn_>
+ <Button_Shadcn_ onClick={() => onChange(range)}>Apply</Button_Shadcn_>
+ </div>
+ </div>
+ )
+}
+
+const filterProperties = [
+ {
+ label: 'Name',
+ name: 'name',
+ type: 'string' as const,
+ operators: ['=', '!=', 'CONTAINS', 'STARTS WITH', 'ENDS WITH'],
+ },
+ {
+ label: 'Status',
+ name: 'status',
+ type: 'string' as const,
+ options: [
+ { label: 'Active', value: 'active' },
+ { label: 'Inactive', value: 'inactive' },
+ { label: 'Pending', value: 'pending' },
+ ],
+ operators: ['=', '!='],
+ },
+ {
+ label: 'Type',
+ name: 'type',
+ type: 'string' as const,
+ options: async (search?: string) => {
+ await new Promise((resolve) => setTimeout(resolve, 500))
+ const allOptions = ['user', 'admin', 'guest']
+ return search
+ ? allOptions.filter((option) => option.toLowerCase().includes(search.toLowerCase()))
+ : allOptions
+ },
+ operators: ['=', '!='],
+ },
+ {
+ label: 'Time period',
+ name: 'created_at',
+ type: 'date' as const,
+ options: [
+ { label: 'Today', value: format(new Date(), 'yyyy-MM-dd') },
+ { label: 'Yesterday', value: format(new Date(Date.now() - 86400000), 'yyyy-MM-dd') },
+ { label: 'Last 7 days', value: format(new Date(Date.now() - 7 * 86400000), 'yyyy-MM-dd') },
+ { label: 'Last 30 days', value: format(new Date(Date.now() - 30 * 86400000), 'yyyy-MM-dd') },
+ {
+ label: 'Pick a date...',
+ component: (props: CustomOptionProps) => <CustomDatePicker {...props} />,
+ },
+ ],
+ operators: ['=', '!=', '>', '<', '>=', '<='],
+ },
+ {
+ label: 'Priority',
+ name: 'priority',
+ type: 'number' as const,
+ options: {
+ component: (props: CustomOptionProps) => (
+ <div className="p-6">
+ <Button onClick={() => props.onChange('1')}>Custom value</Button>
+ </div>
+ ),
+ },
+ triggerOnPropertyClick: true,
+ operators: ['=', '!=', '>', '<', '>=', '<='],
+ },
+]
+
+const initialFilters: FilterGroup = {
+ logicalOperator: 'AND',
+ conditions: [],
+}
+
+export default function FilterBarDemo() {
+ const [filters, setFilters] = useState<FilterGroup>(initialFilters)
+ const [freeformText, setFreeformText] = useState('')
+
+ return (
+ <div className="w-full">
+ <FilterBar
+ filterProperties={filterProperties}
+ freeformText={freeformText}
+ onFreeformTextChange={setFreeformText}
+ filters={filters}
+ onFilterChange={setFilters}
+ />
+ </div>
+ )
+}
diff --git a/apps/design-system/registry/examples.ts b/apps/design-system/registry/examples.ts
index 2198f2527af..b79b6322d44 100644
--- a/apps/design-system/registry/examples.ts
+++ b/apps/design-system/registry/examples.ts
@@ -467,6 +467,12 @@ export const examples: Registry = [
registryDependencies: ['dropdown-menu', 'radio-group'],
files: ['example/dropdown-menu-radio-group.tsx'],
},
+ {
+ name: 'filter-bar-demo',
+ type: 'components:example',
+ registryDependencies: ['filter-bar'],
+ files: ['example/filter-bar-demo.tsx'],
+ },
{
name: 'hover-card-demo',
type: 'components:example',
diff --git a/apps/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx b/apps/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
index 76f8b95560c..cdd3a78d9ce 100644
--- a/apps/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
+++ b/apps/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
@@ -28,6 +28,8 @@ import {
import type { Filters, LogSearchCallback, LogTemplate, QueryType } from './Logs.types'
import { maybeShowUpgradePrompt } from './Logs.utils'
import UpgradePrompt from './UpgradePrompt'
+import { useFlag } from 'hooks/ui/useFlag'
+import { PreviewFilterPanelWithUniversal } from './PreviewFilterPanelWithUniversal'
/**
* Acts as a container component for the entire log display
@@ -58,6 +60,8 @@ export const LogsPreviewer = ({
EmptyState,
filterPanelClassName,
}: PropsWithChildren<LogsPreviewerProps>) => {
+ const useUniversalFilterBar = useFlag('universalFilterBar')
+
const router = useRouter()
const { db } = useParams()
const organization = useSelectedOrganization()
@@ -186,39 +190,48 @@ export const LogsPreviewer = ({
}
}, [db, isSuccess])
+ // Common props shared between both filter panel components to avoid duplication
+ const filterPanelProps = {
+ className: filterPanelClassName,
+ csvData: logData,
+ isLoading,
+ newCount,
+ onRefresh: handleRefresh,
+ onSearch: handleSearch,
+ defaultSearchValue: search,
+ defaultToValue: timestampEnd,
+ defaultFromValue: timestampStart,
+ queryUrl: `/project/${projectRef}/logs/explorer?q=${encodeURIComponent(
+ params.sql || ''
+ )}&its=${encodeURIComponent(timestampStart)}&ite=${encodeURIComponent(timestampEnd)}`,
+ onSelectTemplate,
+ filters,
+ onFiltersChange: setFilters,
+ table,
+ condensedLayout,
+ isShowingEventChart: showChart,
+ onToggleEventChart: () => setShowChart(!showChart),
+ onSelectedDatabaseChange: (id: string) => {
+ setFilters({ ...filters, database: id !== projectRef ? id : undefined })
+ const { db, ...params } = router.query
+ router.push({
+ pathname: router.pathname,
+ query: id !== projectRef ? { ...router.query, db: id } : params,
+ })
+ },
+ selectedDatePickerValue,
+ setSelectedDatePickerValue,
+ }
+
return (
<div className="flex-1 flex flex-col h-full">
- <PreviewFilterPanel
- className={filterPanelClassName}
- csvData={logData}
- isLoading={isLoading}
- newCount={newCount}
- onRefresh={handleRefresh}
- onSearch={handleSearch}
- defaultSearchValue={search}
- defaultToValue={timestampEnd}
- defaultFromValue={timestampStart}
- queryUrl={`/project/${projectRef}/logs/explorer?q=${encodeURIComponent(
- params.sql || ''
- )}&its=${encodeURIComponent(timestampStart)}&ite=${encodeURIComponent(timestampEnd)}`}
- onSelectTemplate={onSelectTemplate}
- filters={filters}
- onFiltersChange={setFilters}
- table={table}
- condensedLayout={condensedLayout}
- isShowingEventChart={showChart}
- onToggleEventChart={() => setShowChart(!showChart)}
- onSelectedDatabaseChange={(id: string) => {
- setFilters({ ...filters, database: id !== projectRef ? id : undefined })
- const { db, ...params } = router.query
- router.push({
- pathname: router.pathname,
- query: id !== projectRef ? { ...router.query, db: id } : params,
- })
- }}
- selectedDatePickerValue={selectedDatePickerValue}
- setSelectedDatePickerValue={setSelectedDatePickerValue}
- />
+ {useUniversalFilterBar ? (
+ // Experimental Universal Filter Bar
+ <PreviewFilterPanelWithUniversal {...filterPanelProps} />
+ ) : (
+ // Legacy Filter Panel
+ <PreviewFilterPanel {...filterPanelProps} />
+ )}
{children}
<div
className={
diff --git a/apps/studio/components/interfaces/Settings/Logs/PreviewFilterPanelWithUniversal.tsx b/apps/studio/components/interfaces/Settings/Logs/PreviewFilterPanelWithUniversal.tsx
new file mode 100644
index 00000000000..ab7f5ae19c8
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Logs/PreviewFilterPanelWithUniversal.tsx
@@ -0,0 +1,381 @@
+import dayjs from 'dayjs'
+import { Eye, EyeOff, RefreshCw, Terminal } from 'lucide-react'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+
+import { useParams } from 'common'
+// import CSVButton from 'components/ui/CSVButton'
+import DatabaseSelector from 'components/ui/DatabaseSelector'
+import { useLoadBalancersQuery } from 'data/read-replicas/load-balancers-query'
+import { IS_PLATFORM } from 'lib/constants'
+import { Button, Calendar, Tooltip, TooltipContent, TooltipTrigger, cn } from 'ui'
+import type {
+ CustomOptionProps,
+ FilterCondition,
+ FilterGroup,
+ FilterProperty,
+} from 'ui-patterns/FilterBar'
+import { FilterBar } from 'ui-patterns/FilterBar'
+import { DatePickerValue } from './Logs.DatePickers'
+import { FILTER_OPTIONS, LOG_ROUTES_WITH_REPLICA_SUPPORT, LogsTableName } from './Logs.constants'
+import type { Filters, LogSearchCallback, LogTemplate } from './Logs.types'
+
+interface CustomDateRangePickerProps {
+ value?: { from: Date; to?: Date }
+ onChange: (range: { from: Date; to?: Date } | undefined) => void
+}
+
+function CustomDateRangePicker({ onChange, onCancel }: CustomOptionProps) {
+ const [dateRange, setDateRange] = useState<any | undefined>()
+
+ return (
+ <div className="w-full space-y-4">
+ <Calendar
+ initialFocus
+ mode="range"
+ defaultMonth={dateRange?.from}
+ selected={dateRange}
+ onSelect={setDateRange}
+ numberOfMonths={2}
+ />
+ <div className="flex justify-end gap-2 py-3 px-4 border-t">
+ <Button type="default" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button
+ type="primary"
+ onClick={() => {
+ if (dateRange?.from) {
+ const from = dayjs(dateRange.from).toISOString()
+ const to = dateRange.to ? dayjs(dateRange.to).toISOString() : dayjs().toISOString()
+ onChange(`${from}|${to}`)
+ }
+ }}
+ >
+ Apply
+ </Button>
+ </div>
+ </div>
+ )
+}
+
+interface PreviewFilterPanelProps {
+ defaultSearchValue?: string
+ defaultToValue?: string
+ defaultFromValue?: string
+ templates?: any
+ isLoading: boolean
+ newCount: number
+ onRefresh?: () => void
+ onSearch?: LogSearchCallback
+ onExploreClick?: () => void
+ queryUrl: string
+ onSelectTemplate: (template: LogTemplate) => void
+ table: LogsTableName
+ condensedLayout: Boolean
+ isShowingEventChart: boolean
+ onToggleEventChart: () => void
+ csvData?: unknown[]
+ onFiltersChange: (filters: Filters) => void
+ filters: Filters
+ onSelectedDatabaseChange: (id: string) => void
+ className?: string
+ selectedDatePickerValue: DatePickerValue
+ setSelectedDatePickerValue: (value: DatePickerValue) => void
+}
+
+function useDebounce<T extends (...args: any[]) => void>(callback: T, delay: number) {
+ const timeoutRef = useRef<NodeJS.Timeout>()
+
+ useEffect(() => {
+ return () => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current)
+ }
+ }
+ }, [])
+
+ return useCallback(
+ (...args: Parameters<T>) => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current)
+ }
+
+ timeoutRef.current = setTimeout(() => {
+ callback(...args)
+ }, delay)
+ },
+ [callback, delay]
+ ) as T
+}
+
+const PreviewFilterPanelWithUniversal = ({
+ isLoading,
+ newCount,
+ onRefresh,
+ onSearch = () => {},
+ defaultSearchValue = '',
+ defaultFromValue,
+ defaultToValue,
+ onExploreClick,
+ queryUrl,
+ condensedLayout,
+ isShowingEventChart,
+ onToggleEventChart,
+ csvData,
+ onFiltersChange,
+ filters,
+ table,
+ onSelectedDatabaseChange,
+ className,
+ selectedDatePickerValue,
+ setSelectedDatePickerValue,
+}: PreviewFilterPanelProps) => {
+ const router = useRouter()
+ const { ref } = useParams()
+
+ const logName = router.pathname.split('/').pop()
+
+ const { data: loadBalancers } = useLoadBalancersQuery({ projectRef: ref })
+
+ const showDatabaseSelector =
+ IS_PLATFORM && LOG_ROUTES_WITH_REPLICA_SUPPORT.includes(router.pathname)
+
+ const filterProperties = useMemo(() => {
+ const tableFilters = FILTER_OPTIONS[table]
+ if (!tableFilters) return []
+
+ const properties: FilterProperty[] = []
+
+ // Add date range filter
+ properties.push({
+ label: 'Time Range',
+ name: 'timerange',
+ type: 'string' as const,
+ operators: ['='],
+ options: [
+ {
+ label: 'Last 15 minutes',
+ value: `${dayjs().subtract(15, 'minute').toISOString()}|${dayjs().toISOString()}`,
+ },
+ {
+ label: 'Last 30 minutes',
+ value: `${dayjs().subtract(30, 'minute').toISOString()}|${dayjs().toISOString()}`,
+ },
+ {
+ label: 'Last hour',
+ value: `${dayjs().subtract(1, 'hour').toISOString()}|${dayjs().toISOString()}`,
+ },
+ {
+ label: 'Last 3 hours',
+ value: `${dayjs().subtract(3, 'hour').toISOString()}|${dayjs().toISOString()}`,
+ },
+ {
+ label: 'Last 24 hours',
+ value: `${dayjs().subtract(24, 'hour').toISOString()}|${dayjs().toISOString()}`,
+ },
+ {
+ label: 'Custom Range...',
+ component: (props: CustomOptionProps) => <CustomDateRangePicker {...props} />,
+ },
+ ],
+ })
+
+ // Add table-specific filters
+ Object.entries(tableFilters).forEach(([key, filterSet]) => {
+ properties.push({
+ label: filterSet.label,
+ name: filterSet.key,
+ type: 'string' as const,
+ operators: ['='],
+ options: filterSet.options.map((option) => ({
+ label: option.label,
+ value: option.key,
+ description: option.description,
+ })),
+ })
+ })
+
+ return properties
+ }, [table])
+
+ // Convert Logs.Filters to FilterBar.FilterGroup
+ const filterBarFilters = useMemo(() => {
+ const conditions: FilterCondition[] = []
+
+ // Handle date range - only add from defaultValues if no timerange filter exists
+ if ((defaultFromValue || defaultToValue) && !filters.timerange) {
+ conditions.push({
+ propertyName: 'timerange',
+ operator: '=',
+ value: `${defaultFromValue || ''}|${defaultToValue || ''}`,
+ })
+ }
+
+ // Convert other filters
+ Object.entries(filters).forEach(([key, value]) => {
+ if (key === 'search_query') return // Skip search_query as it's handled in freeform text
+
+ if (typeof value === 'object' && value !== null) {
+ // If the filter object is empty, add a condition with no value
+ if (Object.keys(value).length === 0) {
+ conditions.push({
+ propertyName: key,
+ operator: '=',
+ value: '',
+ })
+ return
+ }
+
+ // Handle active filters
+ Object.entries(value as Record<string, boolean>).forEach(([subKey, isEnabled]) => {
+ if (isEnabled) {
+ conditions.push({
+ propertyName: key,
+ operator: '=',
+ value: subKey,
+ })
+ }
+ })
+ } else if (value !== undefined && value !== null) {
+ conditions.push({
+ propertyName: key,
+ operator: '=',
+ value: String(value),
+ })
+ }
+ })
+
+ return {
+ logicalOperator: 'AND',
+ conditions,
+ } as FilterGroup
+ }, [filters, defaultFromValue, defaultToValue])
+
+ const handleFilterChange = (filterGroup: FilterGroup) => {
+ const newFilters: Filters = {}
+ let hasTimeRange = false
+
+ filterGroup.conditions.forEach((condition) => {
+ if (!('propertyName' in condition)) return
+
+ const propertyName = condition.propertyName
+ if (!propertyName) return
+
+ if (propertyName === 'timerange') {
+ hasTimeRange = true
+ if (condition.value) {
+ const value = String(condition.value)
+ const [from, to] = value.split('|')
+ newFilters.timerange = { [value]: true }
+ onSearch('datepicker-change', { from, to })
+ } else {
+ newFilters.timerange = {}
+ onSearch('datepicker-change', { from: '', to: '' })
+ }
+ } else {
+ if (!newFilters[propertyName]) {
+ newFilters[propertyName] = {}
+ }
+
+ if (!condition.value) {
+ return
+ }
+
+ ;(newFilters[propertyName] as Record<string, boolean>)[condition.value] = true
+ }
+ })
+
+ // If timerange was completely removed from the filter group
+ if (!hasTimeRange) {
+ onSearch('datepicker-change', { from: '', to: '' })
+ }
+
+ onFiltersChange(newFilters)
+ }
+
+ return (
+ <div className={cn('flex w-full flex-col gap-2', condensedLayout ? ' p-3' : '', className)}>
+ <div className="flex items-center justify-between gap-x-2">
+ <div className="flex-1">
+ <FilterBar
+ filterProperties={filterProperties}
+ filters={filterBarFilters}
+ onFilterChange={handleFilterChange}
+ freeformText={defaultSearchValue}
+ onFreeformTextChange={(value) => onSearch('search-input-change', { query: value })}
+ />
+ </div>
+
+ <div className="flex items-center gap-x-2">
+ <Button
+ title="refresh"
+ type="default"
+ className="px-1.5"
+ icon={
+ <div className="relative">
+ {newCount > 0 && (
+ <div className="absolute -top-3 right-3 flex items-center justify-center">
+ <div className="absolute z-20">
+ <p style={{ fontSize: '0.6rem' }} className="text-white">
+ {newCount > 1000 ? `${Math.floor(newCount / 100) / 10}K` : newCount}
+ </p>
+ </div>
+ <div className="h-4 w-4 animate-ping rounded-full bg-green-800 opacity-60"></div>
+ <div className="z-60 absolute top-0 right-0 h-full w-full rounded-full bg-green-900 opacity-80"></div>
+ </div>
+ )}
+ <RefreshCw />
+ </div>
+ }
+ loading={isLoading}
+ disabled={isLoading}
+ onClick={onRefresh}
+ />
+
+ <Button
+ type="default"
+ onClick={() => onToggleEventChart()}
+ icon={isShowingEventChart ? <Eye /> : <EyeOff />}
+ >
+ Chart
+ </Button>
+
+ {/* <CSVButton data={csvData} disabled={!Boolean(csvData)} title="Download data" /> */}
+
+ {showDatabaseSelector ? (
+ <>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button asChild className="px-1.5" type="default" icon={<Terminal />}>
+ <Link href={queryUrl} />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="text-xs">
+ Open query in Logs Explorer
+ </TooltipContent>
+ </Tooltip>
+ <DatabaseSelector
+ onSelectId={onSelectedDatabaseChange}
+ additionalOptions={
+ table === LogsTableName.EDGE
+ ? (loadBalancers ?? []).length > 0
+ ? [{ id: `${ref}-all`, name: 'API Load Balancer' }]
+ : []
+ : []
+ }
+ />
+ </>
+ ) : (
+ <Button asChild type="default" onClick={onExploreClick}>
+ <Link href={queryUrl}>Explore via query</Link>
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export { PreviewFilterPanelWithUniversal }
diff --git a/packages/ui-patterns/FilterBar/FilterBar.tsx b/packages/ui-patterns/FilterBar/FilterBar.tsx
new file mode 100644
index 00000000000..f1aa41910af
--- /dev/null
+++ b/packages/ui-patterns/FilterBar/FilterBar.tsx
@@ -0,0 +1,1044 @@
+'use client'
+
+import React, { useRef, KeyboardEvent, useMemo, useState, useCallback, useEffect } from 'react'
+import { Search, Sparkles } from 'lucide-react'
+import {
+ Command_Shadcn_,
+ CommandEmpty_Shadcn_,
+ CommandGroup_Shadcn_,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ Dialog,
+ DialogContent,
+} from 'ui'
+import { FilterGroup as FilterGroupComponent } from './FilterGroup'
+import {
+ FilterProperty,
+ FilterCondition,
+ FilterGroup,
+ CustomOptionProps,
+ FilterOption,
+ CustomOptionObject,
+ FilterOptionObject,
+ AsyncOptionsFunction,
+ SyncOptionsFunction,
+} from './types'
+
+export type ActiveInput =
+ | { type: 'value'; path: number[] }
+ | { type: 'operator'; path: number[] }
+ | { type: 'group'; path: number[] }
+ | null
+
+type CommandItem = {
+ value: string
+ label: string
+ icon?: React.ReactNode
+ isCustom?: boolean
+ customOption?: (props: CustomOptionProps) => React.ReactElement
+}
+
+function isCustomOptionObject(option: any): option is CustomOptionObject {
+ return typeof option === 'object' && 'component' in option
+}
+
+function isFilterOptionObject(option: any): option is FilterOptionObject {
+ return typeof option === 'object' && 'value' in option && 'label' in option
+}
+
+function isAsyncOptionsFunction(
+ options: FilterProperty['options']
+): options is AsyncOptionsFunction {
+ if (!options || Array.isArray(options) || isCustomOptionObject(options)) return false
+ return typeof options === 'function' && options.constructor.name === 'AsyncFunction'
+}
+
+function isSyncOptionsFunction(options: FilterProperty['options']): options is SyncOptionsFunction {
+ if (!options || Array.isArray(options) || isCustomOptionObject(options)) return false
+ return typeof options === 'function'
+}
+
+function isGroup(condition: FilterCondition | FilterGroup): condition is FilterGroup {
+ return 'logicalOperator' in condition
+}
+
+export type FilterBarProps = {
+ filterProperties: FilterProperty[]
+ onFilterChange: (filters: FilterGroup) => void
+ freeformText: string
+ onFreeformTextChange: (freeformText: string) => void
+ filters: FilterGroup
+ aiApiUrl?: string
+}
+
+export function FilterBar({
+ filterProperties,
+ filters: activeFilters,
+ onFilterChange,
+ freeformText,
+ onFreeformTextChange,
+ aiApiUrl,
+}: FilterBarProps) {
+ const [isLoading, setIsLoading] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const commandRef = useRef<HTMLDivElement>(null)
+ const [selectedCommandIndex, setSelectedCommandIndex] = useState(0)
+ const [isCommandMenuVisible, setIsCommandMenuVisible] = useState(false)
+ const hideTimeoutRef = useRef<NodeJS.Timeout | null>(null)
+ const [activeInput, setActiveInput] = useState<ActiveInput>(null)
+ const newPathRef = useRef<number[]>([])
+ const [loadingOptions, setLoadingOptions] = useState<Record<string, boolean>>({})
+ const [propertyOptionsCache, setPropertyOptionsCache] = useState<
+ Record<string, { options: (string | FilterOptionObject)[]; searchValue: string }>
+ >({})
+ const loadTimeoutRef = useRef<NodeJS.Timeout | null>(null)
+ const [dialogContent, setDialogContent] = useState<React.ReactElement | null>(null)
+ const [isDialogOpen, setIsDialogOpen] = useState(false)
+ const [pendingPath, setPendingPath] = useState<number[] | null>(null)
+
+ const findGroupByPath = (group: FilterGroup, path: number[]): FilterGroup | null => {
+ if (path.length === 0) return group
+
+ const [current, ...rest] = path
+ const condition = group.conditions[current]
+ if (!condition) return null
+
+ if (rest.length === 0) {
+ return isGroup(condition) ? condition : null
+ }
+
+ if (isGroup(condition)) {
+ return findGroupByPath(condition, rest)
+ }
+
+ return null
+ }
+
+ const findConditionByPath = (group: FilterGroup, path: number[]): FilterCondition | null => {
+ if (path.length === 0) return null
+
+ const [current, ...rest] = path
+ const condition = group.conditions[current]
+ if (!condition) return null
+
+ if (rest.length === 0) {
+ return isGroup(condition) ? null : condition
+ }
+
+ if (isGroup(condition)) {
+ return findConditionByPath(condition, rest)
+ }
+
+ return null
+ }
+
+ const handleInputChange = useCallback(
+ (path: number[], value: string) => {
+ console.log('handleInputChange called with path:', path, 'value:', value)
+ const updateNestedValue = (
+ group: FilterGroup,
+ currentPath: number[],
+ newValue: string
+ ): FilterGroup => {
+ if (currentPath.length === 1) {
+ console.log('Updating value at path level 1:', currentPath[0], 'newValue:', newValue)
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, i) =>
+ i === currentPath[0] ? { ...condition, value: newValue } : condition
+ ),
+ }
+ }
+
+ const [current, ...rest] = currentPath
+ console.log('Updating nested value at path:', current, 'remaining path:', rest)
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, i) =>
+ i === current
+ ? isGroup(condition)
+ ? updateNestedValue(condition, rest, newValue)
+ : condition
+ : condition
+ ),
+ }
+ }
+
+ const updatedFilters = updateNestedValue(activeFilters, path, value)
+ console.log('Updated filters:', updatedFilters)
+ onFilterChange(updatedFilters)
+ setSelectedCommandIndex(0)
+ setIsCommandMenuVisible(true)
+ },
+ [activeFilters]
+ )
+
+ const handleOperatorChange = useCallback(
+ (path: number[], value: string) => {
+ const updateNestedOperator = (
+ group: FilterGroup,
+ currentPath: number[],
+ newOperator: string
+ ): FilterGroup => {
+ if (currentPath.length === 1) {
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, i) =>
+ i === currentPath[0] ? { ...condition, operator: newOperator } : condition
+ ),
+ }
+ }
+
+ const [current, ...rest] = currentPath
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, i) =>
+ i === current
+ ? isGroup(condition)
+ ? updateNestedOperator(condition, rest, newOperator)
+ : condition
+ : condition
+ ),
+ }
+ }
+
+ const updatedFilters = updateNestedOperator(activeFilters, path, value)
+ onFilterChange(updatedFilters)
+ setSelectedCommandIndex(0)
+ setIsCommandMenuVisible(true)
+ },
+ [activeFilters]
+ )
+
+ const handleInputFocus = useCallback((path: number[]) => {
+ setActiveInput({ type: 'value', path })
+ setIsCommandMenuVisible(true)
+ if (hideTimeoutRef.current) {
+ clearTimeout(hideTimeoutRef.current)
+ }
+ }, [])
+
+ const handleOperatorFocus = useCallback((path: number[]) => {
+ setActiveInput({ type: 'operator', path })
+ setIsCommandMenuVisible(true)
+ if (hideTimeoutRef.current) {
+ clearTimeout(hideTimeoutRef.current)
+ }
+ }, [])
+
+ const handleGroupFreeformFocus = useCallback((path: number[]) => {
+ setActiveInput({ type: 'group', path })
+ setIsCommandMenuVisible(true)
+ if (hideTimeoutRef.current) {
+ clearTimeout(hideTimeoutRef.current)
+ }
+ }, [])
+
+ const handleInputBlur = useCallback(() => {
+ if (hideTimeoutRef.current) {
+ clearTimeout(hideTimeoutRef.current)
+ }
+ hideTimeoutRef.current = setTimeout(() => {
+ setIsCommandMenuVisible(false)
+ setActiveInput(null)
+ }, 150)
+ }, [])
+
+ const handleAIFilter = async () => {
+ if (!activeInput || activeInput.type !== 'group' || !aiApiUrl) return
+
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const response = await fetch(aiApiUrl, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ prompt: freeformText,
+ filterProperties,
+ currentPath: activeInput.path,
+ }),
+ })
+
+ if (!response.ok) {
+ const errorData = await response.json()
+ throw new Error(errorData.error || 'AI filtering failed')
+ }
+
+ const data = await response.json()
+ console.log(data)
+ if (!data || !Array.isArray(data.conditions)) {
+ throw new Error('Invalid response from AI filter')
+ }
+
+ // Process the nested structure
+ const processConditions = (conditions: any[]): any[] => {
+ return conditions.map((condition) => {
+ if (isGroup(condition)) {
+ // This is a group
+ return {
+ logicalOperator: condition.logicalOperator,
+ conditions: processConditions(condition.conditions),
+ }
+ } else {
+ // This is a condition
+ const matchedProperty = filterProperties.find(
+ (prop) => prop.name === condition.propertyName
+ )
+ if (!matchedProperty) {
+ throw new Error(`Invalid property: ${condition.propertyName}`)
+ }
+ return {
+ propertyName: matchedProperty.name,
+ value: condition.value,
+ operator: condition.operator || '=',
+ }
+ }
+ })
+ }
+
+ const processedGroup = {
+ logicalOperator: data.logicalOperator || 'AND',
+ conditions: processConditions(data.conditions),
+ }
+
+ // Update the active filters by replacing the group at the current path
+ const updateGroupAtPath = (
+ group: FilterGroup,
+ path: number[],
+ newGroup: FilterGroup
+ ): FilterGroup => {
+ if (path.length === 0) {
+ return newGroup
+ }
+
+ const [current, ...rest] = path
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, index) =>
+ index === current
+ ? updateGroupAtPath(condition as FilterGroup, rest, newGroup)
+ : condition
+ ),
+ }
+ }
+
+ const updatedFilters = updateGroupAtPath(activeFilters, activeInput.path, processedGroup)
+ onFilterChange(updatedFilters)
+
+ onFreeformTextChange('')
+ setIsCommandMenuVisible(false)
+ } catch (error: any) {
+ console.error('Error in AI filtering:', error)
+ setError(error.message || 'AI filtering failed. Please try again.')
+ onFreeformTextChange('')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const handleGroupFreeformChange = useCallback((path: number[], value: string) => {
+ onFreeformTextChange(value)
+ setSelectedCommandIndex(0)
+ setIsCommandMenuVisible(true)
+ }, [])
+
+ const addFilterToGroup = useCallback(
+ (group: FilterGroup, path: number[], property: FilterProperty): FilterGroup => {
+ if (path.length === 0) {
+ return {
+ ...group,
+ conditions: [
+ ...group.conditions,
+ { propertyName: property.name, value: null, operator: '=' },
+ ],
+ }
+ }
+
+ const [current, ...rest] = path
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, i) =>
+ i === current ? addFilterToGroup(condition as FilterGroup, rest, property) : condition
+ ),
+ }
+ },
+ []
+ )
+
+ const addGroupToGroup = useCallback((group: FilterGroup, path: number[]): FilterGroup => {
+ if (path.length === 0) {
+ return {
+ ...group,
+ conditions: [...group.conditions, { logicalOperator: 'AND', conditions: [] }],
+ }
+ }
+
+ const [current, ...rest] = path
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, i) =>
+ i === current ? addGroupToGroup(condition as FilterGroup, rest) : condition
+ ),
+ }
+ }, [])
+
+ const handleCustomOptionSelect = useCallback(
+ (property: FilterProperty, path: number[]) => {
+ if (property.options && isCustomOptionObject(property.options)) {
+ const element = property.options.component({
+ onChange: (value: string) => {
+ handleInputChange(path, value)
+ setIsDialogOpen(false)
+ setDialogContent(null)
+ setPendingPath(null)
+ },
+ onCancel: () => {
+ setIsDialogOpen(false)
+ setDialogContent(null)
+ setPendingPath(null)
+ },
+ search: freeformText,
+ })
+ setDialogContent(element)
+ setIsDialogOpen(true)
+ setPendingPath(path)
+ }
+ },
+ [handleInputChange, freeformText]
+ )
+
+ const updateNestedFilter = (
+ group: FilterGroup,
+ path: number[],
+ updateFn: (condition: FilterCondition) => FilterCondition
+ ): FilterGroup => {
+ if (path.length === 1) {
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, index) =>
+ index === path[0] ? updateFn(condition as FilterCondition) : condition
+ ),
+ }
+ }
+
+ const [current, ...rest] = path
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, index) =>
+ index === current && isGroup(condition)
+ ? updateNestedFilter(condition, rest, updateFn)
+ : condition
+ ),
+ }
+ }
+
+ const handleCommandSelect = (selectedValue: string) => {
+ if (selectedValue === 'ai-filter') {
+ handleAIFilter()
+ return
+ }
+
+ if (selectedValue === 'group') {
+ if (activeInput && activeInput.type === 'group') {
+ const currentPath = activeInput.path
+ const group = findGroupByPath(activeFilters, currentPath)
+ if (!group) return
+
+ const updatedFilters = addGroupToGroup(activeFilters, currentPath)
+ onFilterChange(updatedFilters)
+ newPathRef.current = [...currentPath, group.conditions.length]
+ setTimeout(() => {
+ setActiveInput({ type: 'group', path: newPathRef.current })
+ setIsCommandMenuVisible(true)
+ }, 0)
+ onFreeformTextChange('')
+ }
+ return
+ }
+
+ if (activeInput && activeInput.type === 'value') {
+ const path = activeInput.path
+ const selectedItem = commandItems.find((item) => item.value === selectedValue) as
+ | CommandItem
+ | undefined
+
+ if (selectedItem?.isCustom && selectedItem.customOption) {
+ const element = selectedItem.customOption({
+ onChange: (value: string) => {
+ console.log('onChange:', path, value)
+ handleInputChange(path, value)
+ setIsDialogOpen(false)
+ setDialogContent(null)
+ setPendingPath(null)
+ setTimeout(() => {
+ setActiveInput({ type: 'group', path: path.slice(0, -1) })
+ setIsCommandMenuVisible(true)
+ }, 0)
+ },
+ onCancel: () => {
+ setIsDialogOpen(false)
+ setDialogContent(null)
+ setPendingPath(null)
+ setTimeout(() => {
+ setActiveInput({ type: 'group', path: path.slice(0, -1) })
+ setIsCommandMenuVisible(true)
+ }, 0)
+ },
+ search: freeformText,
+ })
+ setDialogContent(element)
+ setIsDialogOpen(true)
+ setPendingPath(path)
+ } else {
+ handleInputChange(path, selectedValue)
+ setTimeout(() => {
+ setActiveInput({ type: 'group', path: path.slice(0, -1) })
+ setIsCommandMenuVisible(true)
+ }, 0)
+ }
+ } else if (activeInput && activeInput.type === 'operator') {
+ const path = activeInput.path
+ handleOperatorChange(path, selectedValue)
+ setActiveInput(null)
+ } else if (activeInput && activeInput.type === 'group') {
+ const selectedProperty = filterProperties.find((p) => p.name === selectedValue)
+ if (selectedProperty) {
+ const currentPath = activeInput.path
+ const group = findGroupByPath(activeFilters, currentPath)
+ if (!group) return
+
+ // Check if the property itself is a custom option object
+ if (
+ selectedProperty.options &&
+ !Array.isArray(selectedProperty.options) &&
+ isCustomOptionObject(selectedProperty.options)
+ ) {
+ // Add the filter first
+ const updatedFilters = addFilterToGroup(activeFilters, currentPath, selectedProperty)
+ onFilterChange(updatedFilters)
+ const newPath = [...currentPath, group.conditions.length]
+
+ // Show the custom component immediately
+ const element = selectedProperty.options.component({
+ onChange: (value: string) => {
+ console.log('Custom component onChange called with value:', value)
+ console.log('Current active input path:', newPath)
+ // Update the filter with the selected value using the nested update function
+ const filterWithValue = updateNestedFilter(updatedFilters, newPath, (condition) => ({
+ ...condition,
+ propertyName: selectedProperty.name,
+ value: value,
+ operator: '=',
+ }))
+ onFilterChange(filterWithValue)
+ setIsDialogOpen(false)
+ setDialogContent(null)
+ setPendingPath(null)
+ setActiveInput({ type: 'group', path: currentPath })
+ },
+ onCancel: () => {
+ console.log('Custom component onCancel called')
+ removeFilterByPath(newPath)
+ setIsDialogOpen(false)
+ setDialogContent(null)
+ setPendingPath(null)
+ setActiveInput({ type: 'group', path: currentPath })
+ },
+ search: '',
+ })
+ setDialogContent(element)
+ setIsDialogOpen(true)
+ setPendingPath(newPath)
+ setIsCommandMenuVisible(false)
+ } else {
+ // Handle normal array options or async options
+ const updatedFilters = addFilterToGroup(activeFilters, currentPath, selectedProperty)
+ onFilterChange(updatedFilters)
+ const newPath = [...currentPath, group.conditions.length]
+
+ setTimeout(() => {
+ setActiveInput({ type: 'value', path: newPath })
+ setIsCommandMenuVisible(true)
+ }, 0)
+ }
+ onFreeformTextChange('')
+ } else {
+ setError(`Invalid property: ${selectedValue}`)
+ }
+ }
+ }
+
+ const loadPropertyOptions = useCallback(
+ async (property: FilterProperty, search: string = '') => {
+ // Skip if no options or if options is an array or not a function
+ if (
+ !property.options ||
+ Array.isArray(property.options) ||
+ !isAsyncOptionsFunction(property.options)
+ )
+ return
+
+ // Check if we have cached options for this exact search
+ const cached = propertyOptionsCache[property.name]
+ if (cached && cached.searchValue === search) return
+
+ // Clear any pending loads
+ if (loadTimeoutRef.current) {
+ clearTimeout(loadTimeoutRef.current)
+ }
+
+ // Debounce the load
+ loadTimeoutRef.current = setTimeout(async () => {
+ if (loadingOptions[property.name]) return // Prevent duplicate loads
+
+ try {
+ setLoadingOptions((prev) => ({ ...prev, [property.name]: true }))
+ // We can safely assert this is an AsyncOptionsFunction because we checked above
+ const asyncOptions = property.options as AsyncOptionsFunction
+ const rawOptions = await asyncOptions(search)
+ // Convert string options to FilterOptionObject format
+ const options = rawOptions.map((option: string | FilterOptionObject) =>
+ typeof option === 'string' ? { label: option, value: option } : option
+ )
+ setPropertyOptionsCache((prev) => ({
+ ...prev,
+ [property.name]: { options, searchValue: search },
+ }))
+ } catch (error) {
+ console.error(`Error loading options for ${property.name}:`, error)
+ setError(`Failed to load options for ${property.label}`)
+ } finally {
+ setLoadingOptions((prev) => ({ ...prev, [property.name]: false }))
+ }
+ }, 300) // Debounce time
+ },
+ [loadingOptions, propertyOptionsCache]
+ )
+
+ // Cleanup timeout on unmount
+ useEffect(() => {
+ return () => {
+ if (loadTimeoutRef.current) {
+ clearTimeout(loadTimeoutRef.current)
+ }
+ }
+ }, [])
+
+ const commandItems = useMemo(() => {
+ if (activeInput?.type === 'operator') {
+ const condition = findConditionByPath(activeFilters, activeInput.path)
+ const property = filterProperties.find((p) => p.name === condition?.propertyName)
+ const operatorValue = condition?.operator?.toUpperCase() || ''
+ const availableOperators = property?.operators || ['=']
+ return availableOperators
+ .filter((op) => op.toUpperCase().includes(operatorValue))
+ .map((op) => ({ value: op, label: op, icon: undefined }))
+ }
+
+ const inputValue =
+ activeInput?.type === 'group'
+ ? freeformText
+ : activeInput?.type === 'value'
+ ? findConditionByPath(activeFilters, activeInput.path)?.value?.toString() || ''
+ : ''
+
+ const items: CommandItem[] = []
+
+ if (activeInput?.type === 'group') {
+ items.push(
+ ...filterProperties
+ .filter((prop) => prop.label.toLowerCase().includes(inputValue.toLowerCase()))
+ .map((prop) => ({
+ value: prop.name,
+ label: prop.label,
+ icon: undefined,
+ isCustom: false,
+ }))
+ )
+
+ items.push({
+ value: 'group',
+ label: 'New Group',
+ icon: undefined,
+ })
+
+ if (inputValue.trim().length > 0 && aiApiUrl) {
+ items.push({
+ value: 'ai-filter',
+ label: 'Filter by AI',
+ icon: <Sparkles className="mr-2 h-4 w-4" strokeWidth={1.25} />,
+ })
+ }
+ } else if (activeInput?.type === 'value') {
+ const activeCondition = findConditionByPath(activeFilters, activeInput.path)
+ const property = filterProperties.find((p) => p.name === activeCondition?.propertyName)
+
+ if (property) {
+ // If the property itself is a custom option object, show just one item
+ if (!Array.isArray(property.options) && isCustomOptionObject(property.options)) {
+ items.push({
+ value: 'custom',
+ label: property.options.label || 'Custom...',
+ icon: undefined,
+ isCustom: true,
+ customOption: property.options.component,
+ })
+ } else if (loadingOptions[property.name]) {
+ items.push({
+ value: 'loading',
+ label: 'Loading options...',
+ icon: undefined,
+ })
+ } else if (Array.isArray(property.options)) {
+ items.push(
+ ...property.options
+ .filter((option) => {
+ if (typeof option === 'string') {
+ return option.toLowerCase().includes(inputValue.toLowerCase())
+ }
+ if (isFilterOptionObject(option)) {
+ return option.label.toLowerCase().includes(inputValue.toLowerCase())
+ }
+ if (isCustomOptionObject(option)) {
+ return option.label?.toLowerCase().includes(inputValue.toLowerCase()) ?? true
+ }
+ return true
+ })
+ .map((option) => {
+ if (typeof option === 'string') {
+ return {
+ value: option,
+ label: option,
+ icon: undefined,
+ } as CommandItem
+ }
+ if (isFilterOptionObject(option)) {
+ return {
+ value: option.value,
+ label: option.label,
+ icon: undefined,
+ } as CommandItem
+ }
+ if (isCustomOptionObject(option)) {
+ return {
+ value: 'custom',
+ label: option.label || 'Custom...',
+ icon: undefined,
+ isCustom: true,
+ customOption: option.component,
+ } as CommandItem
+ }
+ return null
+ })
+ .filter((item): item is CommandItem => item !== null)
+ )
+ } else if (propertyOptionsCache[property.name]) {
+ items.push(
+ ...propertyOptionsCache[property.name].options.map((option) => {
+ if (typeof option === 'string') {
+ return {
+ value: option,
+ label: option,
+ icon: undefined,
+ }
+ }
+ return {
+ value: option.value,
+ label: option.label,
+ icon: undefined,
+ }
+ })
+ )
+ }
+
+ // Load options if not cached or if search value has changed
+ if (
+ typeof property.options === 'function' &&
+ !loadingOptions[property.name] &&
+ (!propertyOptionsCache[property.name] ||
+ propertyOptionsCache[property.name].searchValue !== inputValue)
+ ) {
+ loadPropertyOptions(property, inputValue)
+ }
+ }
+ }
+
+ return items
+ }, [
+ activeInput,
+ freeformText,
+ activeFilters,
+ filterProperties,
+ propertyOptionsCache,
+ loadingOptions,
+ loadPropertyOptions,
+ aiApiUrl,
+ ])
+
+ const removeFilterByPath = useCallback(
+ (path: number[]) => {
+ const removeFromGroup = (group: FilterGroup, currentPath: number[]): FilterGroup => {
+ if (currentPath.length === 1) {
+ return {
+ ...group,
+ conditions: group.conditions.filter((_, i) => i !== currentPath[0]),
+ }
+ }
+
+ const [current, ...rest] = currentPath
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, i) =>
+ i === current ? removeFromGroup(condition as FilterGroup, rest) : condition
+ ),
+ }
+ }
+
+ const updatedFilters = removeFromGroup(activeFilters, path)
+ onFilterChange(updatedFilters)
+ },
+ [activeFilters]
+ )
+
+ const removeGroupByPath = useCallback(
+ (path: number[]) => {
+ const removeFromGroup = (group: FilterGroup, currentPath: number[]): FilterGroup => {
+ if (currentPath.length === 1) {
+ return {
+ ...group,
+ conditions: group.conditions.filter((_, i) => i !== currentPath[0]),
+ }
+ }
+
+ const [current, ...rest] = currentPath
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, i) =>
+ i === current ? removeFromGroup(condition as FilterGroup, rest) : condition
+ ),
+ }
+ }
+
+ const updatedFilters = removeFromGroup(activeFilters, path)
+ onFilterChange(updatedFilters)
+ },
+ [activeFilters]
+ )
+
+ const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault()
+ setSelectedCommandIndex((prevIndex) =>
+ prevIndex < commandItems.length - 1 ? prevIndex + 1 : prevIndex
+ )
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault()
+ setSelectedCommandIndex((prevIndex) => (prevIndex > 0 ? prevIndex - 1 : 0))
+ } else if (e.key === 'Enter') {
+ e.preventDefault()
+ if (commandItems[selectedCommandIndex]) {
+ handleCommandSelect(commandItems[selectedCommandIndex].value)
+ }
+ } else if (e.key === 'Backspace') {
+ // Skip backspace handling for operator inputs
+ if (activeInput?.type === 'operator') return
+
+ const inputElement = e.target as HTMLInputElement
+ const isEmpty = inputElement.value === ''
+
+ if (activeInput?.type === 'group' && isEmpty) {
+ e.preventDefault()
+ const group = findGroupByPath(activeFilters, activeInput.path)
+
+ if (group && group.conditions.length > 0) {
+ // Remove the last condition in the group
+ const lastConditionPath = [...activeInput.path, group.conditions.length - 1]
+ removeFilterByPath(lastConditionPath)
+ // Keep focus on the group's input
+ setActiveInput({ type: 'group', path: activeInput.path })
+ } else if (group && group.conditions.length === 0) {
+ // Remove the empty group
+ removeGroupByPath(activeInput.path)
+
+ // Focus the parent group's freeform input
+ if (activeInput.path.length > 0) {
+ setActiveInput({
+ type: 'group',
+ path: activeInput.path.slice(0, -1),
+ })
+ } else {
+ setActiveInput(null)
+ }
+ }
+ } else if (activeInput?.type === 'value' && isEmpty) {
+ const condition = findConditionByPath(activeFilters, activeInput.path)
+ if (condition && !condition.value) {
+ e.preventDefault()
+ removeFilterByPath(activeInput.path)
+
+ // Focus the group's input
+ setActiveInput({
+ type: 'group',
+ path: activeInput.path.slice(0, -1),
+ })
+ }
+ }
+ } else if (e.key === ' ' && activeInput?.type === 'value') {
+ e.preventDefault()
+ setActiveInput({ type: 'group', path: [] })
+ } else if (e.key === 'ArrowLeft') {
+ const inputElement = e.target as HTMLInputElement
+ if (inputElement.selectionStart === 0) {
+ e.preventDefault()
+ if (activeInput?.type === 'value') {
+ const lastIndex = activeInput.path[activeInput.path.length - 1]
+ if (lastIndex > 0) {
+ setActiveInput({
+ type: 'value',
+ path: [...activeInput.path.slice(0, -1), lastIndex - 1],
+ })
+ } else {
+ setActiveInput({
+ type: 'operator',
+ path: activeInput.path,
+ })
+ }
+ } else if (activeInput?.type === 'group') {
+ const group = findGroupByPath(activeFilters, activeInput.path)
+ if (group && group.conditions.length > 0) {
+ // If the group has conditions, select the last one
+ const lastConditionPath = [...activeInput.path, group.conditions.length - 1]
+ setActiveInput({ type: 'value', path: lastConditionPath })
+ } else if (activeInput.path.length > 0) {
+ // If no conditions but has parent, select parent group's input
+ setActiveInput({
+ type: 'group',
+ path: activeInput.path.slice(0, -1),
+ })
+ }
+ }
+ }
+ } else if (e.key === 'ArrowRight') {
+ const inputElement = e.target as HTMLInputElement
+ if (inputElement.selectionStart === inputElement.value.length) {
+ e.preventDefault()
+ if (activeInput?.type === 'value') {
+ const group = findGroupByPath(activeFilters, activeInput.path.slice(0, -1))
+ const lastIndex = activeInput.path[activeInput.path.length - 1]
+ if (group && lastIndex < group.conditions.length - 1) {
+ setActiveInput({
+ type: 'value',
+ path: [...activeInput.path.slice(0, -1), lastIndex + 1],
+ })
+ } else {
+ setActiveInput({
+ type: 'group',
+ path: activeInput.path.slice(0, -1),
+ })
+ }
+ } else if (activeInput?.type === 'operator') {
+ setActiveInput({ type: 'value', path: activeInput.path })
+ }
+ }
+ } else if (e.key === 'Escape') {
+ setIsCommandMenuVisible(false)
+ setActiveInput(null)
+ }
+ }
+
+ const handleLabelClick = useCallback((path: number[]) => {
+ setActiveInput({ type: 'value', path })
+ }, [])
+
+ const handleLogicalOperatorChange = useCallback(
+ (path: number[]) => {
+ const updateNestedLogicalOperator = (
+ group: FilterGroup,
+ currentPath: number[]
+ ): FilterGroup => {
+ if (currentPath.length === 0) {
+ return {
+ ...group,
+ logicalOperator: group.logicalOperator === 'AND' ? 'OR' : 'AND',
+ }
+ }
+
+ const [current, ...rest] = currentPath
+ return {
+ ...group,
+ conditions: group.conditions.map((condition, i) =>
+ i === current
+ ? isGroup(condition)
+ ? updateNestedLogicalOperator(condition, rest)
+ : condition
+ : condition
+ ),
+ }
+ }
+
+ const updatedFilters = updateNestedLogicalOperator(activeFilters, path)
+ onFilterChange(updatedFilters)
+ },
+ [activeFilters]
+ )
+
+ return (
+ <div className="w-full space-y-2 relative">
+ <div className="relative flex items-center w-full">
+ <Search className="absolute left-1 top-1/2 transform -translate-y-1/2 text-foreground-muted w-4 h-4" />
+ <div className="flex-1 flex flex-wrap items-center pl-6 pr-1 py-0 gap-1 h-full">
+ <FilterGroupComponent
+ group={activeFilters}
+ filterProperties={filterProperties}
+ path={[]}
+ isLoading={isLoading}
+ activeInput={activeInput}
+ onOperatorChange={handleOperatorChange}
+ onValueChange={handleInputChange}
+ onOperatorFocus={handleOperatorFocus}
+ onValueFocus={handleInputFocus}
+ onBlur={handleInputBlur}
+ onLabelClick={handleLabelClick}
+ onKeyDown={handleKeyDown}
+ onGroupFreeformChange={handleGroupFreeformChange}
+ onGroupFreeformFocus={handleGroupFreeformFocus}
+ groupFreeformValue={freeformText}
+ isGroupFreeformActive={Boolean(activeInput?.type === 'group')}
+ onLogicalOperatorChange={handleLogicalOperatorChange}
+ />
+ </div>
+ </div>
+ {error && <div className="text-red-500 text-xs mt-1">{error}</div>}
+ {isCommandMenuVisible && !isLoading && activeInput !== null && commandItems.length > 0 && (
+ <Command_Shadcn_ ref={commandRef} className="absolute z-10 w-full h-auto shadow-md">
+ <CommandList_Shadcn_>
+ <CommandEmpty_Shadcn_>No results found.</CommandEmpty_Shadcn_>
+ <CommandGroup_Shadcn_>
+ {commandItems.map((item, index) => (
+ <CommandItem_Shadcn_
+ key={item.value}
+ onSelect={() => handleCommandSelect(item.value)}
+ className={`text-xs font-mono ${
+ index === selectedCommandIndex ? 'bg-surface-400' : ''
+ }`}
+ >
+ {item.icon}
+ {item.label}
+ </CommandItem_Shadcn_>
+ ))}
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ )}
+ <Dialog open={isDialogOpen} onOpenChange={(open: boolean) => setIsDialogOpen(open)}>
+ <DialogContent hideClose className="!w-fit max-w-screen">
+ {dialogContent}
+ </DialogContent>
+ </Dialog>
+ </div>
+ )
+}
diff --git a/packages/ui-patterns/FilterBar/FilterCondition.tsx b/packages/ui-patterns/FilterBar/FilterCondition.tsx
new file mode 100644
index 00000000000..f958534f860
--- /dev/null
+++ b/packages/ui-patterns/FilterBar/FilterCondition.tsx
@@ -0,0 +1,86 @@
+import React, { useRef, useEffect } from 'react'
+import { Input_Shadcn_ } from 'ui'
+import { FilterCondition as FilterConditionType, FilterProperty } from './types'
+
+type FilterConditionProps = {
+ condition: FilterConditionType
+ filterProperties: FilterProperty[]
+ id: string
+ isActive: boolean
+ isOperatorActive: boolean
+ isLoading?: boolean
+ onOperatorChange: (value: string) => void
+ onValueChange: (value: string) => void
+ onOperatorFocus: () => void
+ onValueFocus: () => void
+ onBlur: () => void
+ onLabelClick: () => void
+ onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void
+}
+
+export function FilterCondition({
+ condition,
+ filterProperties,
+ id,
+ isActive,
+ isOperatorActive,
+ isLoading,
+ onOperatorChange,
+ onValueChange,
+ onOperatorFocus,
+ onValueFocus,
+ onBlur,
+ onLabelClick,
+ onKeyDown,
+}: FilterConditionProps) {
+ const operatorRef = useRef<HTMLInputElement>(null)
+ const valueRef = useRef<HTMLInputElement>(null)
+ const property = filterProperties.find((p) => p.name === condition.propertyName)
+
+ useEffect(() => {
+ if (isActive && valueRef.current) {
+ valueRef.current.focus()
+ } else if (isOperatorActive && operatorRef.current) {
+ operatorRef.current.focus()
+ }
+ }, [isActive, isOperatorActive])
+
+ if (!property) return null
+
+ return (
+ <div className="flex items-center rounded px-2 h-6 bg-surface-400">
+ <span className="text-xs font-medium mr-1 font-mono cursor-pointer" onClick={onLabelClick}>
+ {property.label}
+ </span>
+ <Input_Shadcn_
+ ref={operatorRef}
+ value={condition.operator}
+ onChange={(e) => onOperatorChange(e.target.value)}
+ onFocus={onOperatorFocus}
+ onBlur={onBlur}
+ className="border-none bg-transparent p-0 text-xs focus:outline-none focus:ring-0 focus:shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 font-mono h-6 mr-1 text-foreground-light"
+ style={{
+ width: `${Math.max(condition.operator.length, 1)}ch`,
+ minWidth: '1ch',
+ }}
+ disabled={isLoading}
+ aria-label={`Operator for ${property.label}`}
+ />
+ <Input_Shadcn_
+ ref={valueRef}
+ value={condition.value?.toString() || ''}
+ onChange={(e) => onValueChange(e.target.value)}
+ onFocus={onValueFocus}
+ onBlur={onBlur}
+ onKeyDown={onKeyDown}
+ className="border-none bg-transparent p-0 text-xs focus:outline-none focus:ring-0 focus:shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 font-mono h-6"
+ style={{
+ width: `${Math.max(condition.value?.toString().length || 0, 1)}ch`,
+ minWidth: '1ch',
+ }}
+ disabled={isLoading}
+ aria-label={`Value for ${property.label}`}
+ />
+ </div>
+ )
+}
diff --git a/packages/ui-patterns/FilterBar/FilterGroup.tsx b/packages/ui-patterns/FilterBar/FilterGroup.tsx
new file mode 100644
index 00000000000..8cd71755e36
--- /dev/null
+++ b/packages/ui-patterns/FilterBar/FilterGroup.tsx
@@ -0,0 +1,199 @@
+import React, { useState, useRef, useEffect } from 'react'
+import { FilterProperty, FilterGroup as FilterGroupType } from './types'
+import { ActiveInput } from './FilterBar'
+import { FilterCondition } from './FilterCondition'
+import { Input_Shadcn_ } from 'ui'
+
+type FilterGroupProps = {
+ group: FilterGroupType
+ path: number[]
+ isLoading?: boolean
+ filterProperties: FilterProperty[]
+ // Active state
+ activeInput: ActiveInput
+ onOperatorChange: (path: number[], value: string) => void
+ onValueChange: (path: number[], value: string) => void
+ onOperatorFocus: (path: number[]) => void
+ onValueFocus: (path: number[]) => void
+ onBlur: () => void
+ onLabelClick: (path: number[]) => void
+ onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void
+ // Group specific props
+ onGroupFreeformChange: (path: number[], value: string) => void
+ onGroupFreeformFocus: (path: number[]) => void
+ groupFreeformValue: string
+ isGroupFreeformActive: boolean
+ // Logical operator props
+ onLogicalOperatorChange?: (path: number[]) => void
+}
+
+export function FilterGroup({
+ group,
+ path,
+ isLoading,
+ activeInput,
+ filterProperties,
+ onOperatorChange,
+ onValueChange,
+ onOperatorFocus,
+ onValueFocus,
+ onBlur,
+ onLabelClick,
+ onKeyDown,
+ onGroupFreeformChange,
+ onGroupFreeformFocus,
+ groupFreeformValue,
+ isGroupFreeformActive,
+ onLogicalOperatorChange,
+}: FilterGroupProps) {
+ const [localFreeformValue, setLocalFreeformValue] = useState('')
+ const freeformInputRef = useRef<HTMLInputElement>(null)
+ const [isHoveringOperator, setIsHoveringOperator] = useState(false)
+ const isActive =
+ isGroupFreeformActive &&
+ activeInput?.type === 'group' &&
+ path.length === activeInput.path.length &&
+ path.every((v, i) => v === activeInput.path[i])
+
+ // Reset local value when group freeform value is cleared
+ useEffect(() => {
+ if (groupFreeformValue === '') {
+ setLocalFreeformValue('')
+ }
+ }, [groupFreeformValue])
+
+ useEffect(() => {
+ if (isActive && freeformInputRef.current) {
+ freeformInputRef.current.focus()
+ }
+ }, [isActive])
+
+ const handleFreeformChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ setLocalFreeformValue(e.target.value)
+ onGroupFreeformChange(path, e.target.value)
+ }
+
+ const handleLogicalOperatorClick = () => {
+ onLogicalOperatorChange?.(path)
+ }
+
+ const handleLogicalOperatorMouseEnter = () => {
+ setIsHoveringOperator(true)
+ }
+
+ const handleLogicalOperatorMouseLeave = () => {
+ setIsHoveringOperator(false)
+ }
+
+ const isConditionActive = (conditionPath: number[]) => {
+ if (!activeInput) return false
+ return (
+ activeInput.type === 'value' &&
+ conditionPath.length === activeInput.path.length &&
+ conditionPath.every((v, i) => v === activeInput.path[i])
+ )
+ }
+
+ const isOperatorActive = (conditionPath: number[]) => {
+ if (!activeInput) return false
+ return (
+ activeInput.type === 'operator' &&
+ conditionPath.length === activeInput.path.length &&
+ conditionPath.every((v, i) => v === activeInput.path[i])
+ )
+ }
+
+ return (
+ <div
+ className={`flex items-center gap-1 rounded ${
+ path.length > 0
+ ? "before:content-['('] before:text-foreground-muted after:content-[')'] after:text-foreground-muted"
+ : ''
+ }`}
+ >
+ <div className="flex items-center gap-1">
+ {group.conditions.map((condition, index) => {
+ const currentPath = [...path, index]
+
+ return (
+ <React.Fragment key={index}>
+ {index > 0 && (
+ <span
+ className={`text-xs font-medium cursor-pointer ${
+ isHoveringOperator
+ ? 'bg-surface-400 text-foreground dark:bg-surface-400'
+ : 'text-foreground-muted'
+ }`}
+ onClick={handleLogicalOperatorClick}
+ onMouseEnter={handleLogicalOperatorMouseEnter}
+ onMouseLeave={handleLogicalOperatorMouseLeave}
+ >
+ {group.logicalOperator}
+ </span>
+ )}
+ {/* Render condition or nested group */}
+ {'logicalOperator' in condition ? (
+ <FilterGroup
+ filterProperties={filterProperties}
+ group={condition}
+ path={currentPath}
+ isLoading={isLoading}
+ activeInput={activeInput}
+ onOperatorChange={onOperatorChange}
+ onValueChange={onValueChange}
+ onOperatorFocus={onOperatorFocus}
+ onValueFocus={onValueFocus}
+ onBlur={onBlur}
+ onLabelClick={onLabelClick}
+ onKeyDown={onKeyDown}
+ onGroupFreeformChange={onGroupFreeformChange}
+ onGroupFreeformFocus={onGroupFreeformFocus}
+ groupFreeformValue={groupFreeformValue}
+ isGroupFreeformActive={isGroupFreeformActive}
+ onLogicalOperatorChange={onLogicalOperatorChange}
+ />
+ ) : (
+ <FilterCondition
+ id={`filter-${currentPath.join('-')}`}
+ condition={condition}
+ isActive={isConditionActive(currentPath)}
+ isOperatorActive={isOperatorActive(currentPath)}
+ isLoading={isLoading}
+ onOperatorChange={(value) => onOperatorChange(currentPath, value)}
+ filterProperties={filterProperties}
+ onValueChange={(value) => onValueChange(currentPath, value)}
+ onOperatorFocus={() => onOperatorFocus(currentPath)}
+ onValueFocus={() => onValueFocus(currentPath)}
+ onBlur={onBlur}
+ onLabelClick={() => onLabelClick(currentPath)}
+ onKeyDown={onKeyDown}
+ />
+ )}
+ </React.Fragment>
+ )
+ })}
+ {/* Add freeform input at the end */}
+ <Input_Shadcn_
+ ref={freeformInputRef}
+ value={isActive ? groupFreeformValue : localFreeformValue}
+ onChange={handleFreeformChange}
+ onFocus={() => onGroupFreeformFocus(path)}
+ onBlur={onBlur}
+ onKeyDown={onKeyDown}
+ className="border-none bg-transparent p-0 text-xs focus:outline-none focus:ring-0 focus:shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 font-mono h-6"
+ placeholder={
+ path.length === 0 && group.conditions.length === 0 ? 'Search or filter...' : '+'
+ }
+ disabled={isLoading}
+ style={{
+ width: `${Math.max(
+ (isActive ? groupFreeformValue : localFreeformValue).length || 1,
+ path.length === 0 && group.conditions.length === 0 ? 18 : 1
+ )}ch`,
+ minWidth: path.length === 0 && group.conditions.length === 0 ? '18ch' : '1ch',
+ }}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/packages/ui-patterns/FilterBar/index.ts b/packages/ui-patterns/FilterBar/index.ts
new file mode 100644
index 00000000000..8f852e36afb
--- /dev/null
+++ b/packages/ui-patterns/FilterBar/index.ts
@@ -0,0 +1,2 @@
+export * from './FilterBar'
+export * from './types'
diff --git a/packages/ui-patterns/FilterBar/types.ts b/packages/ui-patterns/FilterBar/types.ts
new file mode 100644
index 00000000000..84be2d517ea
--- /dev/null
+++ b/packages/ui-patterns/FilterBar/types.ts
@@ -0,0 +1,45 @@
+import React from 'react'
+
+export type CustomOptionProps = {
+ onChange: (value: string) => void
+ onCancel: () => void
+ search?: string
+}
+
+export type FilterOptionObject = {
+ label: string
+ value: string
+}
+
+export type CustomOptionObject = {
+ label?: string
+ component: (props: CustomOptionProps) => React.ReactElement
+}
+
+export type FilterOption = string | FilterOptionObject | CustomOptionObject
+
+export type AsyncOptionsFunction = (search?: string) => Promise<(string | FilterOptionObject)[]>
+export type SyncOptionsFunction = (search?: string) => (string | FilterOptionObject)[]
+
+export type FilterProperty = {
+ label: string
+ name: string
+ type: 'string' | 'number' | 'date' | 'boolean'
+ options?: FilterOption[] | AsyncOptionsFunction | SyncOptionsFunction | CustomOptionObject
+ operators?: string[]
+}
+
+export type FilterCondition = {
+ propertyName: string
+ value: string | number | null
+ operator: string
+}
+
+export type FilterGroup = {
+ logicalOperator: 'AND' | 'OR'
+ conditions: (FilterCondition | FilterGroup)[]
+}
+
+export function isGroup(condition: FilterCondition | FilterGroup): condition is FilterGroup {
+ return 'logicalOperator' in condition
+}
diff --git a/packages/ui-patterns/index.tsx b/packages/ui-patterns/index.tsx
index 8bc8556609b..4e3446f5a0f 100644
--- a/packages/ui-patterns/index.tsx
+++ b/packages/ui-patterns/index.tsx
@@ -22,5 +22,6 @@ export * from './PromoToast'
export * from './admonition'
export * from './ComputeBadge'
export * from './TimestampInfo'
+export * from './FilterBar'
export * from './Toc'
export * from './LogsBarChart'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 480833f2069..8a87b8add2e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -22895,7 +22895,7 @@ snapshots:
debug: 4.4.0([email protected])
enhanced-resolve: 5.17.1
eslint: 8.57.0([email protected])
fast-glob: 3.3.2
get-tsconfig: 4.7.2
@@ -22907,7 +22907,7 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
dependencies:
debug: 3.2.7([email protected])
optionalDependencies:
@@ -22934,7 +22934,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.0([email protected])
eslint-import-resolver-node: 0.3.9([email protected])
hasown: 2.0.2
is-core-module: 2.13.1
is-glob: 4.0.3