Skip to content

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

Refactor organization audit logs to use filter bar (#51921)

Joshen Lim1ddb9ac787cb
diff --git a/apps/studio/components/interfaces/Account/AuditLogs.tsx b/apps/studio/components/interfaces/Account/AuditLogs.tsx
index 2a61b8275a7..2cd6a5fde4d 100644
--- a/apps/studio/components/interfaces/Account/AuditLogs.tsx
+++ b/apps/studio/components/interfaces/Account/AuditLogs.tsx
@@ -10,29 +10,24 @@ import dayjs from 'dayjs'
import { RefreshCwIcon } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { cn, ResizablePanel, ResizablePanelGroup } from 'ui'
-import {
- FilterBar,
- isGroup,
- type CustomOptionProps,
- type FilterCondition,
- type FilterGroup,
- type FilterProperty,
-} from 'ui-patterns/FilterBar'
+import { FilterBar, type FilterGroup, type FilterProperty } from 'ui-patterns/FilterBar'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
-import { findMatchingDateHelper, formatDateRange } from '../Settings/Logs/Logs.datePickerHelpers'
-import { DatePickerValue, LogsDatePicker } from '../Settings/Logs/Logs.DatePickers'
import { parseTimeRange, serializeTimeRange } from '../Settings/Logs/Logs.timeRange'
-import { createAuditLogsProjectOption } from './AuditLogsProjectOption'
import { AuditLogDetailsPanel } from '@/components/interfaces/AuditLogs/AuditLogDetailsPanel'
import { getAuditLogColumns } from '@/components/interfaces/AuditLogs/AuditLogs.columns'
import {
- AUDIT_LOG_DATEPICKER_HELPERS,
DATE_FILTER_PROPERTY,
filterByFilterGroup,
+ findDateCondition,
getDefaultAuditLogRange,
PROJECT_FILTER_PROPERTY,
} from '@/components/interfaces/AuditLogs/AuditLogs.utils'
+import {
+ DateRangeOption,
+ formatDateRangeValue,
+} from '@/components/interfaces/AuditLogs/AuditLogsDateRangeOption'
+import { createAuditLogsProjectOption } from '@/components/interfaces/AuditLogs/AuditLogsProjectOption'
import { AuditLogsSelectionHeader } from '@/components/interfaces/AuditLogs/AuditLogsSelectionHeader'
import { AuditLogsTable } from '@/components/interfaces/AuditLogs/AuditLogsTable'
import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'
@@ -45,41 +40,6 @@ import { useProjectsInfiniteQuery } from '@/data/projects/projects-infinite-quer
const CONTENT_PADDING = 'w-full px-6 xl:px-10'
-const DateRangeOption = ({ onChange }: CustomOptionProps) => {
- const defaultHelper =
- AUDIT_LOG_DATEPICKER_HELPERS.find((helper) => helper.default) ?? AUDIT_LOG_DATEPICKER_HELPERS[0]
- return (
- <LogsDatePicker
- hideWarnings
- variant="inline"
- value={{
- from: defaultHelper.calcFrom(),
- to: defaultHelper.calcTo(),
- text: defaultHelper.text,
- isHelper: true,
- }}
- helpers={AUDIT_LOG_DATEPICKER_HELPERS}
- onSubmit={(value: DatePickerValue) =>
- onChange(serializeTimeRange([new Date(value.from), new Date(value.to)]))
- }
- />
- )
-}
-
-const formatDateRangeValue = (value: unknown): string => {
- const range = parseTimeRange(value)
- if (!range) return String(value ?? '')
- const [from, to] = range
- const helper = findMatchingDateHelper(from, to, AUDIT_LOG_DATEPICKER_HELPERS)
- return helper?.text ?? formatDateRange(from.toISOString(), to.toISOString())
-}
-
-const findDateCondition = (group: FilterGroup) =>
- group.conditions.find(
- (condition): condition is FilterCondition =>
- !isGroup(condition) && condition.propertyName === DATE_FILTER_PROPERTY
- )
-
export const AuditLogs = () => {
const [dateRange, setDateRange] = useState(getDefaultAuditLogRange)
@@ -165,6 +125,7 @@ export const AuditLogs = () => {
options: { component: DateRangeOption },
formatValue: formatDateRangeValue,
isAvailable: !hasDateFilter,
+ topLevelOnly: true,
},
]
diff --git a/apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts b/apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts
index 338b88a6ace..485a690dd77 100644
--- a/apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts
+++ b/apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts
@@ -4,12 +4,8 @@ import { isGroup, type FilterCondition, type FilterGroup } from 'ui-patterns/Fil
import type { DatetimeHelper } from '@/components/interfaces/Settings/Logs/Logs.types'
import type { AuditLog } from '@/data/organizations/organization-audit-logs-query'
-export function filterByProjects(logs: AuditLog[], projectRefs: string[]): AuditLog[] {
- if (projectRefs.length === 0) return logs
- return logs.filter((log) => projectRefs.includes(log.project_ref ?? ''))
-}
-
export const PROJECT_FILTER_PROPERTY = 'project'
+export const USER_FILTER_PROPERTY = 'user'
export const DATE_FILTER_PROPERTY = 'date'
const DEFAULT_AUDIT_LOG_RANGE_HOURS = 24
@@ -21,6 +17,12 @@ export const AUDIT_LOG_DATEPICKER_HELPERS: DatetimeHelper[] = [1, 3, 6, 12, 24].
default: hours === DEFAULT_AUDIT_LOG_RANGE_HOURS,
}))
+export const findDateCondition = (group: FilterGroup) =>
+ group.conditions.find(
+ (condition): condition is FilterCondition =>
+ !isGroup(condition) && condition.propertyName === DATE_FILTER_PROPERTY
+ )
+
export const getDefaultAuditLogRange = () => {
const now = dayjs().utc().set('millisecond', 0)
return {
@@ -39,9 +41,12 @@ const matchesGroup = (log: AuditLog, group: FilterGroup): boolean | null => {
const results = group.conditions
.map((condition) => {
if (isGroup(condition)) return matchesGroup(log, condition)
- if (condition.propertyName !== PROJECT_FILTER_PROPERTY) return null
if (isConditionValueEmpty(condition.value)) return null
- return log.project_ref === condition.value
+ if (condition.propertyName === PROJECT_FILTER_PROPERTY)
+ return log.project_ref === condition.value
+ if (condition.propertyName === USER_FILTER_PROPERTY)
+ return log.actor.user_id === condition.value
+ return null
})
.filter((result) => result !== null)
if (results.length === 0) return null
diff --git a/apps/studio/components/interfaces/AuditLogs/AuditLogsDateRangeOption.tsx b/apps/studio/components/interfaces/AuditLogs/AuditLogsDateRangeOption.tsx
new file mode 100644
index 00000000000..747486f7b39
--- /dev/null
+++ b/apps/studio/components/interfaces/AuditLogs/AuditLogsDateRangeOption.tsx
@@ -0,0 +1,44 @@
+import type { CustomOptionProps } from 'ui-patterns/FilterBar'
+
+import { AUDIT_LOG_DATEPICKER_HELPERS } from './AuditLogs.utils'
+import {
+ findMatchingDateHelper,
+ formatDateRange,
+} from '@/components/interfaces/Settings/Logs/Logs.datePickerHelpers'
+import {
+ LogsDatePicker,
+ type DatePickerValue,
+} from '@/components/interfaces/Settings/Logs/Logs.DatePickers'
+import {
+ parseTimeRange,
+ serializeTimeRange,
+} from '@/components/interfaces/Settings/Logs/Logs.timeRange'
+
+export const DateRangeOption = ({ onChange }: CustomOptionProps) => {
+ const defaultHelper =
+ AUDIT_LOG_DATEPICKER_HELPERS.find((helper) => helper.default) ?? AUDIT_LOG_DATEPICKER_HELPERS[0]
+ return (
+ <LogsDatePicker
+ hideWarnings
+ variant="inline"
+ value={{
+ from: defaultHelper.calcFrom(),
+ to: defaultHelper.calcTo(),
+ text: defaultHelper.text,
+ isHelper: true,
+ }}
+ helpers={AUDIT_LOG_DATEPICKER_HELPERS}
+ onSubmit={(value: DatePickerValue) =>
+ onChange(serializeTimeRange([new Date(value.from), new Date(value.to)]))
+ }
+ />
+ )
+}
+
+export const formatDateRangeValue = (value: unknown): string => {
+ const range = parseTimeRange(value)
+ if (!range) return String(value ?? '')
+ const [from, to] = range
+ const helper = findMatchingDateHelper(from, to, AUDIT_LOG_DATEPICKER_HELPERS)
+ return helper?.text ?? formatDateRange(from.toISOString(), to.toISOString())
+}
diff --git a/apps/studio/components/interfaces/Account/AuditLogsProjectOption.tsx b/apps/studio/components/interfaces/AuditLogs/AuditLogsProjectOption.tsx
similarity index 70%
rename from apps/studio/components/interfaces/Account/AuditLogsProjectOption.tsx
rename to apps/studio/components/interfaces/AuditLogs/AuditLogsProjectOption.tsx
index 8a7e963a4c6..4145d8d993c 100644
--- a/apps/studio/components/interfaces/Account/AuditLogsProjectOption.tsx
+++ b/apps/studio/components/interfaces/AuditLogs/AuditLogsProjectOption.tsx
@@ -5,18 +5,21 @@ import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from 'u
import type { CustomOptionProps } from 'ui-patterns/FilterBar'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
-import {
- useProjectsInfiniteQuery,
- type ProjectInfoInfinite,
-} from '@/data/projects/projects-infinite-query'
+import { useOrgProjectsInfiniteQuery } from '@/data/projects/org-projects-infinite-query'
+import { useProjectsInfiniteQuery } from '@/data/projects/projects-infinite-query'
+
+type AuditLogsProject = { ref: string; name: string }
interface AuditLogsProjectOptionProps extends CustomOptionProps {
- onSelectProject: (project: ProjectInfoInfinite) => void
+ // Scopes the list to an organization's projects, otherwise lists all of the user's projects
+ slug?: string
+ onSelectProject: (project: AuditLogsProject) => void
}
// Select-only project list for the FilterBar. The stored value is the project ref, while the
// chip shows the name through the property's `formatValue`.
export const AuditLogsProjectOption = ({
+ slug,
onChange,
onSelectProject,
}: AuditLogsProjectOptionProps) => {
@@ -25,8 +28,17 @@ export const AuditLogsProjectOption = ({
const [sentinelRef, entry] = useIntersectionObserver({ threshold: 0, rootMargin: '0px' })
+ const isOrgScoped = !!slug
+ const variables = { search: search.length === 0 ? search : debouncedSearch }
+ const accountQuery = useProjectsInfiniteQuery(variables, {
+ placeholderData: keepPreviousData,
+ enabled: !isOrgScoped,
+ })
+ const orgQuery = useOrgProjectsInfiniteQuery(
+ { slug, ...variables },
+ { placeholderData: keepPreviousData, enabled: isOrgScoped }
+ )
const {
- data,
error,
isLoading,
isError,
@@ -35,11 +47,16 @@ export const AuditLogsProjectOption = ({
isFetchingNextPage,
hasNextPage,
fetchNextPage,
- } = useProjectsInfiniteQuery(
- { search: search.length === 0 ? search : debouncedSearch },
- { placeholderData: keepPreviousData }
+ } = isOrgScoped ? orgQuery : accountQuery
+ const accountProjects = useMemo(
+ () => accountQuery.data?.pages.flatMap((page) => page.projects) ?? [],
+ [accountQuery.data?.pages]
+ )
+ const orgProjects = useMemo(
+ () => orgQuery.data?.pages.flatMap((page) => page.projects) ?? [],
+ [orgQuery.data?.pages]
)
- const projects = useMemo(() => data?.pages.flatMap((page) => page.projects) ?? [], [data?.pages])
+ const projects: AuditLogsProject[] = isOrgScoped ? orgProjects : accountProjects
useEffect(() => {
if (entry?.isIntersecting && hasNextPage && !isFetching && !isFetchingNextPage) {
@@ -47,7 +64,7 @@ export const AuditLogsProjectOption = ({
}
}, [entry?.isIntersecting, hasNextPage, isFetching, isFetchingNextPage, fetchNextPage])
- const handleSelect = (project: ProjectInfoInfinite) => {
+ const handleSelect = (project: AuditLogsProject) => {
onSelectProject(project)
onChange(project.ref)
}
@@ -105,12 +122,14 @@ export const AuditLogsProjectOption = ({
}
// FilterBar invokes `component(props)` as a plain function, so this factory returns that function
-// with `onSelectProject` bound, keeping the component itself defined at module level.
+// with `onSelectProject` (and optionally `slug`) bound, keeping the component itself defined at
+// module level.
export const createAuditLogsProjectOption = (
- onSelectProject: AuditLogsProjectOptionProps['onSelectProject']
+ onSelectProject: AuditLogsProjectOptionProps['onSelectProject'],
+ slug?: string
) => {
const renderProjectOption = (props: CustomOptionProps) => (
- <AuditLogsProjectOption {...props} onSelectProject={onSelectProject} />
+ <AuditLogsProjectOption {...props} slug={slug} onSelectProject={onSelectProject} />
)
return renderProjectOption
}
diff --git a/apps/studio/components/interfaces/AuditLogs/AuditLogsUserOption.tsx b/apps/studio/components/interfaces/AuditLogs/AuditLogsUserOption.tsx
new file mode 100644
index 00000000000..d28587db29d
--- /dev/null
+++ b/apps/studio/components/interfaces/AuditLogs/AuditLogsUserOption.tsx
@@ -0,0 +1,65 @@
+import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from 'ui'
+import type { CustomOptionProps } from 'ui-patterns/FilterBar'
+import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
+
+import { useOrganizationMembersQuery } from '@/data/organizations/organization-members-query'
+
+interface AuditLogsUserOptionProps extends CustomOptionProps {
+ slug?: string
+}
+
+// Select-only member list for the FilterBar. The stored value is the member's gotrue_id, while
+// the chip shows the username through the property's `formatValue`.
+export const AuditLogsUserOption = ({ slug, onChange }: AuditLogsUserOptionProps) => {
+ const { data, error, isLoading, isError, isSuccess } = useOrganizationMembersQuery({ slug })
+ const members = (data ?? []).filter((member) => !member.invited_at && !!member.gotrue_id)
+
+ return (
+ <Command>
+ <CommandInput
+ showResetIcon
+ placeholder="Find member..."
+ className="text-base sm:text-sm"
+ // FilterBar keeps focus on the chip's input, so move it here for cmdk's arrow/enter keys
+ autoFocus
+ />
+ <CommandList className="max-h-[300px] overflow-y-auto overflow-x-hidden">
+ <CommandGroup>
+ {isLoading && (
+ <div className="px-2 py-1">
+ <ShimmeringLoader className="py-2" />
+ </div>
+ )}
+ {isError && (
+ <p className="text-xs text-center text-foreground-lighter py-3">
+ Failed to retrieve members: {error.message}
+ </p>
+ )}
+ {isSuccess && members.length === 0 && (
+ <p className="text-xs text-center text-foreground-lighter py-3">No members found</p>
+ )}
+ {isSuccess &&
+ members.map((member) => (
+ <CommandItem
+ key={member.gotrue_id}
+ value={`${member.username.replaceAll('"', '')}-${member.gotrue_id}`}
+ className="cursor-pointer w-full"
+ onSelect={() => onChange(member.gotrue_id)}
+ >
+ {member.username}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ )
+}
+
+// FilterBar invokes `component(props)` as a plain function, so this factory returns that function
+// with `slug` bound, keeping the component itself defined at module level.
+export const createAuditLogsUserOption = (slug?: string) => {
+ const renderUserOption = (props: CustomOptionProps) => (
+ <AuditLogsUserOption {...props} slug={slug} />
+ )
+ return renderUserOption
+}
diff --git a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
index 08c4a1d4b03..6b2d3c21020 100644
--- a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
+++ b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
@@ -7,7 +7,6 @@ import {
type RowSelectionState,
type SortingState,
} from '@tanstack/react-table'
-import { useDebounce } from '@uidotdev/usehooks'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { RefreshCwIcon } from 'lucide-react'
@@ -21,19 +20,34 @@ import {
ResizablePanelGroup,
WarningIcon,
} from 'ui'
+import { FilterBar, type FilterGroup, type FilterProperty } from 'ui-patterns/FilterBar'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
-import { filterByUsers } from './AuditLogs.utils'
import { AuditLogDetailsPanel } from '@/components/interfaces/AuditLogs/AuditLogDetailsPanel'
import { getAuditLogColumns } from '@/components/interfaces/AuditLogs/AuditLogs.columns'
-import { filterByProjects } from '@/components/interfaces/AuditLogs/AuditLogs.utils'
+import {
+ DATE_FILTER_PROPERTY,
+ filterByFilterGroup,
+ findDateCondition,
+ getDefaultAuditLogRange,
+ PROJECT_FILTER_PROPERTY,
+ USER_FILTER_PROPERTY,
+} from '@/components/interfaces/AuditLogs/AuditLogs.utils'
+import {
+ DateRangeOption,
+ formatDateRangeValue,
+} from '@/components/interfaces/AuditLogs/AuditLogsDateRangeOption'
+import { createAuditLogsProjectOption } from '@/components/interfaces/AuditLogs/AuditLogsProjectOption'
import { AuditLogsSelectionHeader } from '@/components/interfaces/AuditLogs/AuditLogsSelectionHeader'
import { AuditLogsTable } from '@/components/interfaces/AuditLogs/AuditLogsTable'
-import { LogsDatePicker } from '@/components/interfaces/Settings/Logs/Logs.DatePickers'
+import { createAuditLogsUserOption } from '@/components/interfaces/AuditLogs/AuditLogsUserOption'
+import {
+ parseTimeRange,
+ serializeTimeRange,
+} from '@/components/interfaces/Settings/Logs/Logs.timeRange'
import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'
import { AlertError } from '@/components/ui/AlertError'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
-import { FilterPopover } from '@/components/ui/FilterPopover'
import { NoPermission } from '@/components/ui/NoPermission'
import { UpgradeToPro } from '@/components/ui/UpgradeToPro'
import {
@@ -48,25 +62,41 @@ import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganizati
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
-const CONTENT_PADDING = 'w-full px-6 xl:px-10'
+const CONTENT_PADDING = 'w-full px-6 xl:px-9'
const logsUpgradeError = 'upgrade to Team or Enterprise Plan to access audit logs.'
export const AuditLogs = () => {
const { slug } = useParams()
- const currentTime = dayjs().utc().set('millisecond', 0)
-
- const [search, setSearch] = useState('')
- const debouncedSearch = useDebounce(search, 500)
- const [dateRange, setDateRange] = useState({
- from: currentTime.subtract(1, 'day').toISOString(),
- to: currentTime.toISOString(),
- })
+ const [dateRange, setDateRange] = useState(getDefaultAuditLogRange)
const [selectedLog, setSelectedLog] = useState<AuditLog>()
- const [filters, setFilters] = useState<{ users: string[]; projects: string[] }>({
- users: [], // gotrue_id[]
- projects: [], // project_ref[]
- })
+ const [filterGroup, setFilterGroup] = useState<FilterGroup>(() => ({
+ logicalOperator: 'AND',
+ conditions: [
+ {
+ propertyName: DATE_FILTER_PROPERTY,
+ operator: '=',
+ value: serializeTimeRange([new Date(dateRange.from), new Date(dateRange.to)]),
+ },
+ ],
+ }))
+ const [freeformText, setFreeformText] = useState('')
+ const [projectNames, setProjectNames] = useState<Record<string, string>>({})
+
+ const handleSelectProject = (project: { ref: string; name: string }) =>
+ setProjectNames((prev) => ({ ...prev, [project.ref]: project.name }))
+
+ const handleFilterChange = (next: FilterGroup) => {
+ setFilterGroup(next)
+ // The API call is driven by `dateRange`, so keep it in sync with the date chip
+ const dateCondition = findDateCondition(next)
+ if (!dateCondition) {
+ setDateRange(getDefaultAuditLogRange())
+ return
+ }
+ const range = parseTimeRange(dateCondition.value)
+ if (range) setDateRange({ from: range[0].toISOString(), to: range[1].toISOString() })
+ }
const { can: canReadAuditLogs, isLoading: isLoadingPermissions } = useAsyncCheckPermissions(
PermissionAction.READ,
@@ -106,15 +136,8 @@ export const AuditLogs = () => {
const isRangeExceededError = isError && error.message.includes('range exceeded')
const showFilters = !isLoading && !isLogsNotAvailableBasedOnPlan
- const {
- data: projectsData,
- isPending: isLoadingProjects,
- isFetching: isFetchingProjects,
- isFetchingNextPage,
- hasNextPage,
- fetchNextPage,
- } = useOrgProjectsInfiniteQuery(
- { slug, search: search.length === 0 ? search : debouncedSearch },
+ const { data: projectsData, isPending: isLoadingProjects } = useOrgProjectsInfiniteQuery(
+ { slug },
{ placeholderData: keepPreviousData, enabled: showFilters }
)
const projects = useMemo(
@@ -130,13 +153,45 @@ export const AuditLogs = () => {
)
const { data: members } = useOrganizationMembersQuery({ slug }, { enabled: showFilters })
- const activeMembers = (members ?? []).filter((x) => !x.invited_at)
const logs = useMemo(() => data?.result ?? [], [data?.result])
- const filteredLogs = useMemo(
- () => filterByProjects(filterByUsers(logs, filters.users), filters.projects),
- [logs, filters.users, filters.projects]
- )
+ const filteredLogs = useMemo(() => filterByFilterGroup(logs, filterGroup), [logs, filterGroup])
+
+ const hasDateFilter = !!findDateCondition(filterGroup)
+ const filterProperties: FilterProperty[] = [
+ {
+ label: 'User',
+ name: USER_FILTER_PROPERTY,
+ type: 'string',
+ operators: ['='],
+ options: { component: createAuditLogsUserOption(slug) },
+ formatValue: (value) => {
+ const id = String(value ?? '')
+ return members?.find((member) => member.gotrue_id === id)?.username ?? id
+ },
+ },
+ {
+ label: 'Project',
+ name: PROJECT_FILTER_PROPERTY,
+ type: 'string',
+ operators: ['='],
+ options: { component: createAuditLogsProjectOption(handleSelectProject, slug) },
+ formatValue: (value) => {
+ const ref = String(value ?? '')
+ return projectNames[ref] ?? projects.find((p) => p.ref === ref)?.name ?? ref
+ },
+ },
+ {
+ label: 'Date range',
+ name: DATE_FILTER_PROPERTY,
+ type: 'date',
+ operators: [{ label: 'Equals', value: '=', group: 'comparison' }],
+ options: { component: DateRangeOption },
+ formatValue: formatDateRangeValue,
+ isAvailable: !hasDateFilter,
+ topLevelOnly: true,
+ },
+ ]
const lastSelectedRowId = useRef<string | null>(null)
const columns = useMemo(
@@ -176,7 +231,7 @@ export const AuditLogs = () => {
useEffect(() => {
setRowSelection({})
lastSelectedRowId.current = null
- }, [filters.users, filters.projects])
+ }, [filterGroup])
// This feature depends on the subscription tier of the user.
// The API limits the logs to maximum of 62 days and 5 minutes so when the page is
@@ -214,84 +269,7 @@ export const AuditLogs = () => {
return (
<ScaffoldContainer size="full" className="px-0 h-full flex flex-col">
<ScaffoldSection isFullWidth className="pt-6! pb-0! flex-1 min-h-0">
- <div className="space-y-4 flex flex-col h-full min-h-0">
- {showFilters && (
- <div
- className={cn(
- CONTENT_PADDING,
- 'flex flex-col md:flex-row md:items-center justify-between'
- )}
- >
- <div className="flex items-center space-x-2">
- <p className="text-xs prose">Filter by</p>
- <FilterPopover
- name="Users"
- options={activeMembers}
- labelKey="username"
- valueKey="gotrue_id"
- activeOptions={filters.users}
- onSaveFilters={(values) => setFilters({ ...filters, users: values })}
- />
- <FilterPopover
- name="Projects"
- options={projects}
- labelKey="name"
- valueKey="ref"
- activeOptions={filters.projects}
- onSaveFilters={(values) => setFilters({ ...filters, projects: values })}
- search={search}
- setSearch={setSearch}
- hasNextPage={hasNextPage}
- isLoading={isLoadingProjects}
- isFetching={isFetchingProjects}
- isFetchingNextPage={isFetchingNextPage}
- fetchNextPage={fetchNextPage}
- searchPlaceholder="Search for a project..."
- />
- <LogsDatePicker
- hideWarnings
- value={dateRange}
- onSubmit={(value) => setDateRange(value)}
- helpers={[
- {
- text: 'Last 1 hour',
- calcFrom: () => dayjs().subtract(1, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 3 hours',
- calcFrom: () => dayjs().subtract(3, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 6 hours',
- calcFrom: () => dayjs().subtract(6, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 12 hours',
- calcFrom: () => dayjs().subtract(12, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 24 hours',
- calcFrom: () => dayjs().subtract(1, 'day').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- ]}
- />
- </div>
- <ButtonTooltip
- disabled={isLoading}
- loading={isLoading || isRefetching}
- className="w-7"
- icon={<RefreshCwIcon />}
- onClick={() => refetch()}
- tooltip={{ content: { side: 'bottom', text: 'Refresh logs' } }}
- />
- </div>
- )}
-
+ <div className="flex flex-col h-full min-h-0">
{shouldShowLoadingState && (
<div className={cn(CONTENT_PADDING, 'space-y-2')}>
<ShimmeringLoader />
@@ -325,8 +303,32 @@ export const AuditLogs = () => {
{isSuccess && (
<>
+ {showFilters && (
+ <div className="border-t py-2 pl-1 pr-4 flex flex-col md:flex-row justify-between">
+ <FilterBar
+ supportsOperators
+ variant="pill"
+ defaultGroupOperator="OR"
+ className="bg-transparent border-0 [&>div>div>div>input]:!text-xs [&_[data-testid=filter-bar-freeform-input]]:min-w-64"
+ filterProperties={filterProperties}
+ freeformText={freeformText}
+ filters={filterGroup}
+ onFilterChange={handleFilterChange}
+ onFreeformTextChange={setFreeformText}
+ />
+ <ButtonTooltip
+ disabled={isLoading}
+ loading={isLoading || isRefetching}
+ className="w-7"
+ icon={<RefreshCwIcon />}
+ onClick={() => refetch()}
+ tooltip={{ content: { side: 'bottom', text: 'Refresh logs' } }}
+ />
+ </div>
+ )}
+
{logs.length === 0 ? (
- <div className={CONTENT_PADDING}>
+ <div className={cn(CONTENT_PADDING, 'border-t pt-4')}>
<div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">
<p className="prose text-sm">
Your organization does not have any audit logs available yet
@@ -334,7 +336,7 @@ export const AuditLogs = () => {
</div>
</div>
) : logs.length > 0 && filteredLogs.length === 0 ? (
- <div className={CONTENT_PADDING}>
+ <div className={cn(CONTENT_PADDING, 'border-t pt-4')}>
<div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">
<p className="prose text-sm">
No audit logs found based on the filters applied
diff --git a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts
index 2dbe7990b95..d3f14bc0016 100644
--- a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts
+++ b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts
@@ -1,12 +1,6 @@
import dayjs from 'dayjs'
import { DatePickerToFrom } from '@/components/interfaces/Settings/Logs/Logs.types'
-import type { AuditLog } from '@/data/organizations/organization-audit-logs-query'
-
-export function filterByUsers(logs: AuditLog[], userIds: string[]): AuditLog[] {
- if (userIds.length === 0) return logs
- return logs.filter((log) => userIds.includes(log.actor.user_id ?? ''))
-}
// [Joshen] Mainly to handle if a single date is selected - currently just for Audit Logs as
// i'm on the fence if this logic should be within the DatePicker component itself
diff --git a/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts
index 0a122c71b1c..af8472a32b4 100644
--- a/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts
+++ b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts
@@ -2,11 +2,7 @@ import dayjs from 'dayjs'
import type { FilterGroup } from 'ui-patterns/FilterBar'
import { describe, expect, test } from 'vitest'
-import {
- filterByFilterGroup,
- filterByProjects,
-} from '@/components/interfaces/AuditLogs/AuditLogs.utils'
-import { filterByUsers } from '@/components/interfaces/Organization/AuditLogs/AuditLogs.utils'
+import { filterByFilterGroup } from '@/components/interfaces/AuditLogs/AuditLogs.utils'
import {
TIMESTAMP_MICROS_PER_MS,
type AuditLog,
@@ -56,62 +52,17 @@ describe('timestamp conversion (microseconds → milliseconds)', () => {
})
})
-describe('filterByUsers', () => {
- test('returns all logs when filter list is empty', () => {
- expect(filterByUsers([logA, logB, logC], [])).toEqual([logA, logB, logC])
- })
-
- test('filters to matching user_id', () => {
- const result = filterByUsers([logA, logB, logC], ['user-1'])
- expect(result.map((l) => l.request_id)).toEqual(['req-b'])
- })
-
- test('filters to multiple user_ids', () => {
- const result = filterByUsers([logA, logB, logC], ['user-1', 'user-2'])
- expect(result.map((l) => l.request_id)).toEqual(['req-b', 'req-c'])
- })
-
- test('excludes logs with no user_id when filtering', () => {
- const result = filterByUsers([logA, logB], ['user-1'])
- expect(result.map((l) => l.request_id)).toEqual(['req-b'])
- })
-
- test('returns empty array when no logs match', () => {
- expect(filterByUsers([logA, logB, logC], ['user-unknown'])).toEqual([])
- })
-})
-
-describe('filterByProjects', () => {
- test('returns all logs when filter list is empty', () => {
- expect(filterByProjects([logA, logB, logC], [])).toEqual([logA, logB, logC])
- })
-
- test('filters to matching project_ref', () => {
- const result = filterByProjects([logA, logB, logC], ['proj-1'])
- expect(result.map((l) => l.request_id)).toEqual(['req-a'])
- })
-
- test('filters to multiple project_refs', () => {
- const result = filterByProjects([logA, logB, logC], ['proj-1', 'proj-2'])
- expect(result.map((l) => l.request_id)).toEqual(['req-a', 'req-b'])
- })
-
- test('excludes logs with no project_ref when filtering', () => {
- const result = filterByProjects([logA, logC], ['proj-1'])
- expect(result.map((l) => l.request_id)).toEqual(['req-a'])
- })
-
- test('returns empty array when no logs match', () => {
- expect(filterByProjects([logA, logB, logC], ['proj-unknown'])).toEqual([])
- })
-})
-
describe('filterByFilterGroup', () => {
const project = (value: string) => ({
propertyName: 'project',
operator: '=',
value,
})
+ const user = (value: string) => ({
+ propertyName: 'user',
+ operator: '=',
+ value,
+ })
const date = {
propertyName: 'date',
operator: '=',
@@ -189,4 +140,23 @@ describe('filterByFilterGroup', () => {
'req-c'
)
})
+
+ test('OR matches logs from any of the users', () => {
+ expect(
+ requestIds({ logicalOperator: 'OR', conditions: [user('user-1'), user('user-2')] })
+ ).toEqual(['req-b', 'req-c'])
+ })
+
+ test('excludes logs without a matching actor when a user is selected', () => {
+ expect(requestIds({ logicalOperator: 'AND', conditions: [user('user-unknown')] })).toEqual([])
+ })
+
+ test('combines user and project: user AND project', () => {
+ expect(
+ requestIds({ logicalOperator: 'AND', conditions: [user('user-1'), project('proj-2')] })
+ ).toEqual(['req-b'])
+ expect(
+ requestIds({ logicalOperator: 'AND', conditions: [user('user-2'), project('proj-2')] })
+ ).toEqual([])
+ })
})
diff --git a/packages/ui-patterns/package.json b/packages/ui-patterns/package.json
index dc39da6cb88..840d87000f1 100644
--- a/packages/ui-patterns/package.json
+++ b/packages/ui-patterns/package.json
@@ -367,8 +367,8 @@
"types": "./src/FilterBar/index.ts"
},
"./FilterBar/menuItems": {
- "import": "./src/FilterBar/menuItems.ts",
- "types": "./src/FilterBar/menuItems.ts"
+ "import": "./src/FilterBar/menuItems.tsx",
+ "types": "./src/FilterBar/menuItems.tsx"
},
"./FilterBar/types": {
"import": "./src/FilterBar/types.ts",
@@ -382,10 +382,6 @@
"import": "./src/FilterBar/useCommandHandling.ts",
"types": "./src/FilterBar/useCommandHandling.ts"
},
- "./FilterBar/useCommandMenu": {
- "import": "./src/FilterBar/useCommandMenu.ts",
- "types": "./src/FilterBar/useCommandMenu.ts"
- },
"./FilterBar/useKeyboardNavigation": {
"import": "./src/FilterBar/useKeyboardNavigation.ts",
"types": "./src/FilterBar/useKeyboardNavigation.ts"
diff --git a/packages/ui-patterns/src/FilterBar/DefaultCommandList.test.tsx b/packages/ui-patterns/src/FilterBar/DefaultCommandList.test.tsx
index f6854505391..125362626a7 100644
--- a/packages/ui-patterns/src/FilterBar/DefaultCommandList.test.tsx
+++ b/packages/ui-patterns/src/FilterBar/DefaultCommandList.test.tsx
@@ -10,26 +10,26 @@ const renderList = (items: MenuItem[]) =>
const getSeparators = (container: HTMLElement) => container.querySelectorAll('.h-px')
describe('DefaultCommandList', () => {
- it('renders a separator before "New Group" when it follows other items', () => {
+ it('renders a separator before "New filter group" when it follows other items', () => {
const { container, getByText } = renderList([
{ value: 'project', label: 'Project' },
{ value: 'date', label: 'Date range' },
- { value: '__new_group__', label: 'New Group' },
+ { value: '__new_group__', label: 'New filter group' },
])
const separators = getSeparators(container)
expect(separators).toHaveLength(1)
expect(separators[0].nextElementSibling).toBe(
- getByText('New Group').closest('[cmdk-item], div')
+ getByText('New filter group').closest('[cmdk-item], div')
)
})
- it('does not render a separator when "New Group" is the only item', () => {
- const { container } = renderList([{ value: '__new_group__', label: 'New Group' }])
+ it('does not render a separator when "New filter group" is the only item', () => {
+ const { container } = renderList([{ value: '__new_group__', label: 'New filter group' }])
expect(getSeparators(container)).toHaveLength(0)
})
- it('does not render a separator when there is no "New Group" item', () => {
+ it('does not render a separator when there is no "New filter group" item', () => {
const { container } = renderList([
{ value: 'project', label: 'Project' },
{ value: 'date', label: 'Date range' },
diff --git a/packages/ui-patterns/src/FilterBar/FilterBar.tsx b/packages/ui-patterns/src/FilterBar/FilterBar.tsx
index 33616d2af94..cd1756ec4e8 100644
--- a/packages/ui-patterns/src/FilterBar/FilterBar.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterBar.tsx
@@ -1,6 +1,6 @@
'use client'
-import { Search } from 'lucide-react'
+import { SearchIcon } from 'lucide-react'
import { motion } from 'motion/react'
import React, { forwardRef } from 'react'
import { cn } from 'ui'
@@ -28,7 +28,7 @@ export type FilterBarProps = {
icon?: React.ReactNode
/**
* Name of the property to use when the user commits free text from the root input. Must match
- * a `name` in `filterProperties`. When set, the dropdown shows a "Search <propertyLabel>: \"...\""
+ * a `name` in `filterProperties`. When set, the dropdown shows a "SearchIcon <propertyLabel>: \"...\""
* item as the first option while the user is typing. Selecting it (Enter) creates a filter
* `{ propertyName, operator: '=', value: typedText }`. If the property has no `=` operator,
* the first operator in its list is used instead.
@@ -67,18 +67,18 @@ function FilterBarContent({ className }: { className?: string }) {
>
<div
className={cn(
- 'relative flex items-center justify-center shrink-0 px-2 bg-surface-200 cursor-pointer',
+ 'relative flex items-start justify-center shrink-0 px-2 bg-surface-200 cursor-pointer',
variant === 'pill' ? 'bg-transparent border-r-0' : 'border-r'
)}
onClick={() => handleGroupFreeformFocus([])}
>
<div
className={cn(
- 'transition-opacity duration-300 ease-in-out',
+ 'transition-opacity duration-300 ease-in-out relative top-[4px]',
loadingIcon ? 'opacity-0' : 'opacity-100'
)}
>
- <Search className="text-foreground-muted w-4 h-4 sticky" />
+ <SearchIcon size={16} className="text-foreground-muted" />
</div>
{loadingIcon && (
<div className="absolute inset-0 flex items-center justify-center">{loadingIcon}</div>
diff --git a/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx b/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx
index d6b01935422..62d4f387e07 100644
--- a/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx
@@ -98,7 +98,7 @@ export type FilterBarRootProps = {
actions?: FilterBarAction[]
isLoading?: boolean
supportsOperators?: boolean
- /** Logical operator for groups created via "New Group". Defaults to 'AND'. */
+ /** Logical operator for groups created via "New filter group". Defaults to 'AND'. */
defaultGroupOperator?: FilterGroup['logicalOperator']
variant?: FilterBarVariant
icon?: React.ReactNode
@@ -415,7 +415,7 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
return (
<FilterBarContext.Provider value={contextValue}>
- <div ref={rootRef} data-filterbar-root className="h-full min-h-[32px] flex items-stretch">
+ <div ref={rootRef} data-filterbar-root className="h-full min-h-[26px] flex items-stretch">
{children}
</div>
</FilterBarContext.Provider>
diff --git a/packages/ui-patterns/src/FilterBar/FilterCondition.tsx b/packages/ui-patterns/src/FilterBar/FilterCondition.tsx
index d6a86a5c97f..947389950e6 100644
--- a/packages/ui-patterns/src/FilterBar/FilterCondition.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterCondition.tsx
@@ -117,8 +117,9 @@ export function FilterCondition({
filterProperties,
currentPropertyName: condition.propertyName,
inputValue: propertySearchText,
+ isNested: path.length > 1,
}),
- [filterProperties, condition.propertyName, propertySearchText]
+ [filterProperties, condition.propertyName, propertySearchText, path.length]
)
const {
diff --git a/packages/ui-patterns/src/FilterBar/FilterGroup.tsx b/packages/ui-patterns/src/FilterBar/FilterGroup.tsx
index 29add803ef6..a5153a43775 100644
--- a/packages/ui-patterns/src/FilterBar/FilterGroup.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterGroup.tsx
@@ -105,6 +105,7 @@ export function FilterGroup({ group, path }: FilterGroupProps) {
actions,
supportsOperators,
freeformDefaultProperty: resolvedFreeformDefaultProperty,
+ isNested: path.length > 0,
}),
[
filterProperties,
@@ -114,6 +115,7 @@ export function FilterGroup({ group, path }: FilterGroupProps) {
actions,
supportsOperators,
resolvedFreeformDefaultProperty,
+ path.length,
]
)
@@ -206,7 +208,7 @@ export function FilterGroup({ group, path }: FilterGroupProps) {
onFocus={() => handleGroupFreeformFocus(path)}
onBlur={handleFreeformBlur}
onKeyDown={handleFreeformKeyDown}
- className="relative m-[3px] border-none bg-transparent text-xs hover:border-transparent focus:border-transparent focus-visible:border-transparent focus:outline-hidden focus:ring-0 focus:shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 w-auto flex-1 h-auto min-w-0 px-2 py-1"
+ className="relative mx-[3px] border-none bg-transparent text-xs hover:border-transparent focus:border-transparent focus-visible:border-transparent focus:outline-hidden focus:ring-0 focus:shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 w-auto flex-1 h-auto min-w-0 px-2 py-1"
placeholder={
group.conditions.length === 0 ? emptyPlaceholder : 'Add more filters...'
}
diff --git a/packages/ui-patterns/src/FilterBar/menuItems.test.ts b/packages/ui-patterns/src/FilterBar/menuItems.test.ts
index 19324dd699e..be76957cf68 100644
--- a/packages/ui-patterns/src/FilterBar/menuItems.test.ts
+++ b/packages/ui-patterns/src/FilterBar/menuItems.test.ts
@@ -277,26 +277,60 @@ describe('buildPropertyItems', () => {
expect(items).toEqual([{ value: 'name', label: 'Name' }])
})
- it('uses a sentinel value for the "New Group" action when supportsOperators is true', () => {
+ it('hides topLevelOnly properties in nested groups only', () => {
+ const withTopLevelOnly: FilterProperty[] = [
+ ...properties,
+ { label: 'Date', name: 'date', type: 'date', operators: ['='], topLevelOnly: true },
+ ]
+
+ const rootItems = buildPropertyItems({ filterProperties: withTopLevelOnly, inputValue: '' })
+ const nestedItems = buildPropertyItems({
+ filterProperties: withTopLevelOnly,
+ inputValue: '',
+ isNested: true,
+ })
+
+ expect(rootItems.map((item) => item.value)).toEqual(['name', 'status', 'date'])
+ expect(nestedItems.map((item) => item.value)).toEqual(['name', 'status'])
+ })
+
+ it('hides topLevelOnly properties when changing a nested condition property', () => {
+ const withTopLevelOnly: FilterProperty[] = [
+ ...properties,
+ { label: 'Date', name: 'date', type: 'date', operators: ['='], topLevelOnly: true },
+ ]
+ const params = {
+ filterProperties: withTopLevelOnly,
+ currentPropertyName: 'name',
+ inputValue: '',
+ }
+
+ expect(buildPropertyChangeItems(params).map((item) => item.value)).toEqual(['status', 'date'])
+ expect(
+ buildPropertyChangeItems({ ...params, isNested: true }).map((item) => item.value)
+ ).toEqual(['status'])
+ })
+
+ it('uses a sentinel value for the "New filter group" action when supportsOperators is true', () => {
const items = buildPropertyItems({
filterProperties: properties,
inputValue: '',
supportsOperators: true,
})
- const groupItem = items.find((item) => item.label === 'New Group')
+ const groupItem = items.find((item) => item.label === 'New filter group')
expect(groupItem).toBeDefined()
expect(groupItem?.value).toBe('__new_group__')
})
- it('does not include "New Group" when supportsOperators is false', () => {
+ it('does not include "New filter group" when supportsOperators is false', () => {
const items = buildPropertyItems({
filterProperties: properties,
inputValue: '',
supportsOperators: false,
})
- expect(items.find((item) => item.label === 'New Group')).toBeUndefined()
+ expect(items.find((item) => item.label === 'New filter group')).toBeUndefined()
})
it('does not collide with a property named "group"', () => {
@@ -312,7 +346,7 @@ describe('buildPropertyItems', () => {
})
const groupPropertyItem = items.find((item) => item.label === 'group')
- const newGroupItem = items.find((item) => item.label === 'New Group')
+ const newGroupItem = items.find((item) => item.label === 'New filter group')
expect(groupPropertyItem).toBeDefined()
expect(groupPropertyItem?.value).toBe('group')
diff --git a/packages/ui-patterns/src/FilterBar/menuItems.ts b/packages/ui-patterns/src/FilterBar/menuItems.tsx
similarity index 91%
rename from packages/ui-patterns/src/FilterBar/menuItems.ts
rename to packages/ui-patterns/src/FilterBar/menuItems.tsx
index bf51e899d6b..a8c2b56fc30 100644
--- a/packages/ui-patterns/src/FilterBar/menuItems.ts
+++ b/packages/ui-patterns/src/FilterBar/menuItems.tsx
@@ -1,3 +1,5 @@
+import { ParenthesesIcon } from 'lucide-react'
+
import { ActiveInputState, FilterBarAction, FilterGroup, FilterProperty, MenuItem } from './types'
import {
collectConditions,
@@ -73,10 +75,20 @@ export function buildPropertyItems(params: {
supportsOperators?: boolean
actions?: FilterBarAction[]
freeformDefaultProperty?: FilterProperty
+ /** Whether the menu belongs to a nested group, which hides `topLevelOnly` properties */
+ isNested?: boolean
}): MenuItem[] {
- const { filterProperties, inputValue, supportsOperators, actions, freeformDefaultProperty } =
- params
- const availableProperties = filterProperties.filter((property) => property.isAvailable !== false)
+ const {
+ filterProperties,
+ inputValue,
+ supportsOperators,
+ actions,
+ freeformDefaultProperty,
+ isNested = false,
+ } = params
+ const availableProperties = filterProperties.filter(
+ (property) => property.isAvailable !== false && !(isNested && property.topLevelOnly)
+ )
const items: MenuItem[] = []
const trimmedInput = inputValue.trim()
@@ -101,7 +113,11 @@ export function buildPropertyItems(params: {
)
if (supportsOperators) {
- items.push({ value: '__new_group__', label: 'New Group' })
+ items.push({
+ icon: <ParenthesesIcon size={14} />,
+ value: '__new_group__',
+ label: 'New filter group',
+ })
}
if (actions && trimmedInput.length > 0) {
@@ -124,11 +140,14 @@ export function buildPropertyChangeItems(params: {
filterProperties: FilterProperty[]
currentPropertyName: string
inputValue: string
+ /** Whether the condition is inside a nested group, which hides `topLevelOnly` properties */
+ isNested?: boolean
}): MenuItem[] {
- const { filterProperties, currentPropertyName, inputValue } = params
+ const { filterProperties, currentPropertyName, inputValue, isNested = false } = params
return filterProperties
.filter((property) => property.isAvailable !== false)
+ .filter((property) => !(isNested && property.topLevelOnly))
.filter((prop) => prop.name !== currentPropertyName)
.filter((prop) => prop.label.toLowerCase().includes(inputValue.toLowerCase()))
.map((prop) => ({ value: prop.name, label: prop.label }))
diff --git a/packages/ui-patterns/src/FilterBar/types.ts b/packages/ui-patterns/src/FilterBar/types.ts
index 3a842f9359c..63dda412eff 100644
--- a/packages/ui-patterns/src/FilterBar/types.ts
+++ b/packages/ui-patterns/src/FilterBar/types.ts
@@ -60,6 +60,8 @@ export type FilterProperty = {
operators?: FilterOperator[]
/** Whether this property can be added or selected when changing a filter. Defaults to true. */
isAvailable?: boolean
+ /** Only offer this property in the root group, not inside nested groups. Defaults to false. */
+ topLevelOnly?: boolean
/** Display a readable label while preserving the underlying value for editing. */
formatValue?: (value: FilterCondition['value']) => string
}
diff --git a/packages/ui-patterns/src/FilterBar/useCommandMenu.ts b/packages/ui-patterns/src/FilterBar/useCommandMenu.ts
deleted file mode 100644
index 81b285f7040..00000000000
--- a/packages/ui-patterns/src/FilterBar/useCommandMenu.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import { Sparkles } from 'lucide-react'
-import { useMemo } from 'react'
-import * as React from 'react'
-
-import { ActiveInputState, FilterGroup, FilterProperty } from './types'
-import {
- findConditionByPath,
- isCustomOptionObject,
- isFilterOperatorObject,
- isFilterOptionObject,
-} from './utils'
-
-// Deprecated soon; kept for compatibility during refactor
-
-export type CommandItem = {
- value: string
- label: string
- icon?: React.ReactNode
- isCustom?: boolean
- customOption?: (props: any) => React.ReactElement
-}
-
-export function useCommandMenu({
- activeInput,
- freeformText,
- activeFilters,
- filterProperties,
- propertyOptionsCache,
- loadingOptions,
- aiApiUrl,
- supportsOperators,
-}: {
- activeInput: ActiveInputState
- freeformText: string
- activeFilters: FilterGroup
- filterProperties: FilterProperty[]
- propertyOptionsCache: Record<string, { options: any[]; searchValue: string }>
- loadingOptions: Record<string, boolean>
- aiApiUrl?: string
- supportsOperators: boolean
-}) {
- const commandItems = useMemo(() => {
- if (activeInput?.type === 'operator') {
- return getOperatorItems(activeInput, activeFilters, filterProperties)
- }
-
- const inputValue = getInputValue(activeInput, freeformText, activeFilters)
- const items: CommandItem[] = []
-
- if (activeInput?.type === 'group') {
- items.push(...getPropertyItems(filterProperties, inputValue))
-
- if (supportsOperators) {
- items.push({
- value: '__new_group__',
- label: 'New Group',
- })
- }
-
- if (inputValue.trim().length > 0 && aiApiUrl) {
- items.push({
- value: 'ai-filter',
- label: 'Filter by AI',
- icon: React.createElement(Sparkles, { className: 'mr-2 h-4 w-4', strokeWidth: 1.25 }),
- })
- }
- } else if (activeInput?.type === 'value') {
- items.push(
- ...getValueItems(
- activeInput,
- activeFilters,
- filterProperties,
- propertyOptionsCache,
- loadingOptions,
- inputValue
- )
- )
- }
-
- return items
- }, [
- activeInput,
- freeformText,
- activeFilters,
- filterProperties,
- propertyOptionsCache,
- loadingOptions,
- aiApiUrl,
- supportsOperators,
- ])
-
- return { commandItems }
-}
-
-function getOperatorItems(
- activeInput: Extract<ActiveInputState, { type: 'operator' }>,
- activeFilters: FilterGroup,
- filterProperties: FilterProperty[]
-): CommandItem[] {
- 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) => {
- const searchText = isFilterOperatorObject(op) ? op.value : op
- return searchText.toUpperCase().includes(operatorValue)
- })
- .map((op) => {
- if (isFilterOperatorObject(op)) {
- return { value: op.value, label: op.label }
- }
- return { value: op, label: op }
- })
-}
-
-function getInputValue(
- activeInput: ActiveInputState,
- freeformText: string,
- activeFilters: FilterGroup
-): string {
- return activeInput?.type === 'group'
- ? freeformText
- : activeInput?.type === 'value'
- ? (findConditionByPath(activeFilters, activeInput.path)?.value ?? '').toString()
- : ''
-}
-
-function getPropertyItems(filterProperties: FilterProperty[], inputValue: string): CommandItem[] {
- return filterProperties
- .filter((prop) => prop.label.toLowerCase().includes(inputValue.toLowerCase()))
- .map((prop) => ({
- value: prop.name,
- label: prop.label,
- }))
-}
-
-function getValueItems(
- activeInput: Extract<ActiveInputState, { type: 'value' }>,
- activeFilters: FilterGroup,
- filterProperties: FilterProperty[],
- propertyOptionsCache: Record<string, { options: any[]; searchValue: string }>,
- loadingOptions: Record<string, boolean>,
- inputValue: string
-): CommandItem[] {
- const activeCondition = findConditionByPath(activeFilters, activeInput.path)
- const property = filterProperties.find((p) => p.name === activeCondition?.propertyName)
- const items: CommandItem[] = []
-
- if (!property) return items
-
- // Handle custom option object at property level
- if (!Array.isArray(property.options) && isCustomOptionObject(property.options)) {
- items.push({
- value: 'custom',
- label: property.options.label || 'Custom...',
- isCustom: true,
- customOption: property.options.component,
- })
- } else if (loadingOptions[property.name]) {
- items.push({
- value: 'loading',
- label: 'Loading options...',
- })
- } else if (Array.isArray(property.options)) {
- items.push(...getArrayOptionItems(property.options, inputValue))
- } else if (propertyOptionsCache[property.name]) {
- items.push(...getCachedOptionItems(propertyOptionsCache[property.name].options))
- }
-
- return items
-}
-
-function getArrayOptionItems(options: any[], inputValue: string): CommandItem[] {
- const items: CommandItem[] = []
-
- for (const option of options) {
- if (typeof option === 'string') {
- if (option.toLowerCase().includes(inputValue.toLowerCase())) {
- items.push({
- value: option,
- label: option,
- })
- }
- } else if (isFilterOptionObject(option)) {
- if (option.label.toLowerCase().includes(inputValue.toLowerCase())) {
- items.push({
- value: option.value,
- label: option.label,
- })
- }
- } else if (isCustomOptionObject(option)) {
- if (option.label?.toLowerCase().includes(inputValue.toLowerCase()) ?? true) {
- items.push({
- value: 'custom',
- label: option.label || 'Custom...',
- isCustom: true,
- customOption: option.component,
- })
- }
- }
- }
-
- return items
-}
-
-function getCachedOptionItems(options: any[]): CommandItem[] {
- return options.map((option) => {
- if (typeof option === 'string') {
- return {
- value: option,
- label: option,
- }
- }
- return {
- value: option.value,
- label: option.label,
- }
- })
-}