Skip to content

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

Joshenlim/fe 4510 auditlogs filterbar for account logs (#51790)

Joshen Lim17f21bf6a89a
diff --git a/apps/studio/components/interfaces/Account/AuditLogs.tsx b/apps/studio/components/interfaces/Account/AuditLogs.tsx
index 6240f80e3b1..2a61b8275a7 100644
--- a/apps/studio/components/interfaces/Account/AuditLogs.tsx
+++ b/apps/studio/components/interfaces/Account/AuditLogs.tsx
@@ -6,23 +6,38 @@ import {
type RowSelectionState,
type SortingState,
} from '@tanstack/react-table'
-import { useDebounce } from '@uidotdev/usehooks'
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 { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
-import { LogsDatePicker } from '../Settings/Logs/Logs.DatePickers'
+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 { filterByProjects } from '@/components/interfaces/AuditLogs/AuditLogs.utils'
+import {
+ AUDIT_LOG_DATEPICKER_HELPERS,
+ DATE_FILTER_PROPERTY,
+ filterByFilterGroup,
+ getDefaultAuditLogRange,
+ PROJECT_FILTER_PROPERTY,
+} from '@/components/interfaces/AuditLogs/AuditLogs.utils'
import { AuditLogsSelectionHeader } from '@/components/interfaces/AuditLogs/AuditLogsSelectionHeader'
import { AuditLogsTable } from '@/components/interfaces/AuditLogs/AuditLogsTable'
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 { type AuditLog } from '@/data/organizations/organization-audit-logs-query'
import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
import { useProfileAuditLogsQuery } from '@/data/profile/profile-audit-logs-query'
@@ -30,31 +45,75 @@ import { useProjectsInfiniteQuery } from '@/data/projects/projects-infinite-quer
const CONTENT_PADDING = 'w-full px-6 xl:px-10'
-export const AuditLogs = () => {
- const currentTime = dayjs().utc().set('millisecond', 0)
+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 [search, setSearch] = useState('')
- const debouncedSearch = useDebounce(search, 500)
+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 [dateRange, setDateRange] = useState({
- from: currentTime.subtract(1, 'day').toISOString(),
- to: currentTime.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)
const [selectedLog, setSelectedLog] = useState<AuditLog>()
- const [filters, setFilters] = useState<{ projects: string[] }>({
- projects: [],
- })
+ 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 {
- data: projectsData,
- isPending: isLoadingProjects,
- isFetching: isFetchingProjects,
- isFetchingNextPage,
- hasNextPage,
- fetchNextPage,
- } = useProjectsInfiniteQuery(
- { search: search.length === 0 ? search : debouncedSearch },
+ 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 { data: projectsData, isPending: isLoadingProjects } = useProjectsInfiniteQuery(
+ {},
{ placeholderData: keepPreviousData }
)
const projects = useMemo(
@@ -83,10 +142,31 @@ export const AuditLogs = () => {
)
const logs = useMemo(() => data?.result ?? [], [data?.result])
- const filteredLogs = useMemo(
- () => filterByProjects(logs, filters.projects),
- [logs, filters.projects]
- )
+ const filteredLogs = useMemo(() => filterByFilterGroup(logs, filterGroup), [logs, filterGroup])
+
+ const hasDateFilter = !!findDateCondition(filterGroup)
+ const filterProperties: FilterProperty[] = [
+ {
+ label: 'Project',
+ name: PROJECT_FILTER_PROPERTY,
+ type: 'string',
+ operators: ['='],
+ options: { component: createAuditLogsProjectOption(handleSelectProject) },
+ 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,
+ },
+ ]
const lastSelectedRowId = useRef<string | null>(null)
const columns = useMemo(
@@ -135,76 +215,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">
- {/* [Joshen] Can consider replacing this with filter bar */}
- <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="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">
{isLoading && (
<div className={cn(CONTENT_PADDING, 'space-y-2')}>
<ShimmeringLoader />
@@ -221,6 +232,28 @@ export const AuditLogs = () => {
{isSuccess && (
<>
+ <div className="border-t py-2 pl-1 pr-4 flex flex-col md:flex-row md:items-center 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="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">
diff --git a/apps/studio/components/interfaces/Account/AuditLogsProjectOption.tsx b/apps/studio/components/interfaces/Account/AuditLogsProjectOption.tsx
new file mode 100644
index 00000000000..8a7e963a4c6
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/AuditLogsProjectOption.tsx
@@ -0,0 +1,116 @@
+import { keepPreviousData } from '@tanstack/react-query'
+import { useDebounce, useIntersectionObserver } from '@uidotdev/usehooks'
+import { useEffect, useMemo, useState } from 'react'
+import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from 'ui'
+import type { CustomOptionProps } from 'ui-patterns/FilterBar'
+import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
+
+import {
+ useProjectsInfiniteQuery,
+ type ProjectInfoInfinite,
+} from '@/data/projects/projects-infinite-query'
+
+interface AuditLogsProjectOptionProps extends CustomOptionProps {
+ onSelectProject: (project: ProjectInfoInfinite) => 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 = ({
+ onChange,
+ onSelectProject,
+}: AuditLogsProjectOptionProps) => {
+ const [search, setSearch] = useState('')
+ const debouncedSearch = useDebounce(search, 500)
+
+ const [sentinelRef, entry] = useIntersectionObserver({ threshold: 0, rootMargin: '0px' })
+
+ const {
+ data,
+ error,
+ isLoading,
+ isError,
+ isSuccess,
+ isFetching,
+ isFetchingNextPage,
+ hasNextPage,
+ fetchNextPage,
+ } = useProjectsInfiniteQuery(
+ { search: search.length === 0 ? search : debouncedSearch },
+ { placeholderData: keepPreviousData }
+ )
+ const projects = useMemo(() => data?.pages.flatMap((page) => page.projects) ?? [], [data?.pages])
+
+ useEffect(() => {
+ if (entry?.isIntersecting && hasNextPage && !isFetching && !isFetchingNextPage) {
+ fetchNextPage()
+ }
+ }, [entry?.isIntersecting, hasNextPage, isFetching, isFetchingNextPage, fetchNextPage])
+
+ const handleSelect = (project: ProjectInfoInfinite) => {
+ onSelectProject(project)
+ onChange(project.ref)
+ }
+
+ return (
+ <Command shouldFilter={false}>
+ <CommandInput
+ showResetIcon
+ value={search}
+ onValueChange={setSearch}
+ placeholder="Find project..."
+ handleReset={() => setSearch('')}
+ 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 projects: {error.message}
+ </p>
+ )}
+ {isSuccess && projects.length === 0 && (
+ <p className="text-xs text-center text-foreground-lighter py-3">
+ {search.length > 0 ? 'No projects found based on your search' : 'No projects found'}
+ </p>
+ )}
+ {isSuccess &&
+ projects.map((project) => (
+ <CommandItem
+ key={project.ref}
+ value={`${project.name.replaceAll('"', '')}-${project.ref}`}
+ className="cursor-pointer w-full"
+ onSelect={() => handleSelect(project)}
+ >
+ {project.name}
+ </CommandItem>
+ ))}
+ <div ref={sentinelRef} className="h-1 -mt-1" />
+ {hasNextPage && (
+ <div className="px-2 py-1">
+ <ShimmeringLoader className="py-2" />
+ </div>
+ )}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ )
+}
+
+// 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.
+export const createAuditLogsProjectOption = (
+ onSelectProject: AuditLogsProjectOptionProps['onSelectProject']
+) => {
+ const renderProjectOption = (props: CustomOptionProps) => (
+ <AuditLogsProjectOption {...props} onSelectProject={onSelectProject} />
+ )
+ return renderProjectOption
+}
diff --git a/apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts b/apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts
index c6fbaeb86ce..338b88a6ace 100644
--- a/apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts
+++ b/apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts
@@ -1,6 +1,53 @@
+import dayjs from 'dayjs'
+import { isGroup, type FilterCondition, type FilterGroup } from 'ui-patterns/FilterBar'
+
+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 DATE_FILTER_PROPERTY = 'date'
+
+const DEFAULT_AUDIT_LOG_RANGE_HOURS = 24
+
+export const AUDIT_LOG_DATEPICKER_HELPERS: DatetimeHelper[] = [1, 3, 6, 12, 24].map((hours) => ({
+ text: `Last ${hours} ${hours === 1 ? 'hour' : 'hours'}`,
+ calcFrom: () => dayjs().subtract(hours, 'hour').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ default: hours === DEFAULT_AUDIT_LOG_RANGE_HOURS,
+}))
+
+export const getDefaultAuditLogRange = () => {
+ const now = dayjs().utc().set('millisecond', 0)
+ return {
+ from: now.subtract(DEFAULT_AUDIT_LOG_RANGE_HOURS, 'hour').toISOString(),
+ to: now.toISOString(),
+ }
+}
+
+const isConditionValueEmpty = (value: FilterCondition['value']) =>
+ value === null || value === undefined || value === ''
+
+// Evaluates the filter tree against a log. Conditions that don't narrow rows client-side (empty
+// values, and the date range which the API already applies) are skipped rather than treated as
+// false, so a half-typed chip doesn't blank the table.
+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
+ })
+ .filter((result) => result !== null)
+ if (results.length === 0) return null
+ return group.logicalOperator === 'AND' ? results.every(Boolean) : results.some(Boolean)
+}
+
+export function filterByFilterGroup(logs: AuditLog[], group: FilterGroup): AuditLog[] {
+ return logs.filter((log) => matchesGroup(log, group) !== false)
+}
diff --git a/apps/studio/components/interfaces/AuditLogs/AuditLogsSelectionHeader.tsx b/apps/studio/components/interfaces/AuditLogs/AuditLogsSelectionHeader.tsx
index 6b52c8e8b20..bd18f9661e7 100644
--- a/apps/studio/components/interfaces/AuditLogs/AuditLogsSelectionHeader.tsx
+++ b/apps/studio/components/interfaces/AuditLogs/AuditLogsSelectionHeader.tsx
@@ -30,7 +30,7 @@ export const AuditLogsSelectionHeader = ({ table }: AuditLogsSelectionHeaderProp
animate={{ height: '40px', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ type: 'spring', stiffness: 420, damping: 30, mass: 0.4 }}
- className="px-10 flex items-center justify-between border-b bg-surface-75 w-full overflow-hidden absolute top-0 left-0 right-0 z-20"
+ className="pl-10 pr-4 flex items-center justify-between border-b bg-surface-75 w-full overflow-hidden absolute top-0 left-0 right-0 z-20"
>
<p className="text-xs">
{selectedRows.length} row{selectedRows.length > 1 ? 's' : ''} selected
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.timeRange.test.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.timeRange.test.ts
new file mode 100644
index 00000000000..e5a43c94589
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.timeRange.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest'
+
+import { parseTimeRange, serializeTimeRange } from './Logs.timeRange'
+
+const range: [Date, Date] = [new Date('2026-09-22T02:00:00Z'), new Date('2026-09-22T03:00:00Z')]
+
+describe('serializeTimeRange / parseTimeRange', () => {
+ it('round-trips a date range', () => {
+ expect(parseTimeRange(serializeTimeRange(range))).toEqual(range)
+ })
+
+ it.each([
+ undefined,
+ null,
+ '',
+ 'invalid',
+ '2026-09-22T02:00:00Z',
+ 'invalid – 2026-09-22T03:00:00Z',
+ '2026-09-22T03:00:00Z – 2026-09-22T02:00:00Z',
+ '2026-09-22T02:00:00Z – 2026-09-22T03:00:00Z – 2026-09-22T04:00:00Z',
+ ])('rejects an invalid or incomplete range: %s', (value) => {
+ expect(parseTimeRange(value)).toBeUndefined()
+ })
+})
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.timeRange.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.timeRange.ts
new file mode 100644
index 00000000000..c1e27b5c03e
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.timeRange.ts
@@ -0,0 +1,16 @@
+import { z } from 'zod'
+
+// Date ranges travel through filter bars as a single `from – to` string value.
+const TIME_RANGE_SEPARATOR = ' – '
+
+export const serializeTimeRange = (range: Date[]): string =>
+ range.map((date) => date.toISOString()).join(TIME_RANGE_SEPARATOR)
+
+export const parseTimeRange = (value: unknown): [Date, Date] | undefined => {
+ if (typeof value !== 'string') return
+ const result = z
+ .tuple([z.coerce.date(), z.coerce.date()])
+ .safeParse(value.split(TIME_RANGE_SEPARATOR))
+ if (!result.success || result.data[0] > result.data[1]) return
+ return result.data
+}
diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx
index a373d0a46f9..ee8c2f650b2 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx
@@ -15,11 +15,13 @@ import {
buildFilterGroup,
buildFilterProperties,
getUserFilterValue,
- parseTimeRange,
- serializeTimeRange,
TIME_RANGE_PROPERTY,
USER_PROPERTY,
} from './LogsFilterBar.utils'
+import {
+ parseTimeRange,
+ serializeTimeRange,
+} from '@/components/interfaces/Settings/Logs/Logs.timeRange'
import { searchAuthUsers } from '@/components/interfaces/UserJourneys/UserJourneys.queries'
import { DataTableFilterTimerange } from '@/components/ui/DataTable/DataTableFilters/DataTableFilterTimerange'
import { useDataTable } from '@/components/ui/DataTable/providers/DataTableProvider'
diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.test.ts b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.test.ts
index 84e6d96b040..b23288ea9d4 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.test.ts
+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.test.ts
@@ -8,12 +8,14 @@ import {
filterPropertySchema,
formatTimeRangeValue,
getUserFilterValue,
- parseTimeRange,
- serializeTimeRange,
TIME_RANGE_PROPERTY,
USER_PROPERTY,
type FilterableField,
} from './LogsFilterBar.utils'
+import {
+ parseTimeRange,
+ serializeTimeRange,
+} from '@/components/interfaces/Settings/Logs/Logs.timeRange'
describe('buildFilterProperties', () => {
const fields: FilterableField[] = [
@@ -218,19 +220,6 @@ describe('time range filters', () => {
expect(parseTimeRange(serializeTimeRange(range))).toEqual(range)
})
- it.each([
- undefined,
- null,
- '',
- 'invalid',
- '2026-09-22T02:00:00Z',
- 'invalid – 2026-09-22T03:00:00Z',
- '2026-09-22T03:00:00Z – 2026-09-22T02:00:00Z',
- '2026-09-22T02:00:00Z – 2026-09-22T03:00:00Z – 2026-09-22T04:00:00Z',
- ])('rejects an invalid or incomplete range: %s', (value) => {
- expect(parseTimeRange(value)).toBeUndefined()
- })
-
it('does not wrap dates as ordinary log attribute filters', () => {
const values = buildColumnFilterValues([
{ propertyName: TIME_RANGE_PROPERTY, value: serializeTimeRange(range), operator: '=' },
diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.ts b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.ts
index 2e670062295..02f0bea5814 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.ts
+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.ts
@@ -17,6 +17,10 @@ import {
findMatchingDateHelper,
formatDateRange,
} from '@/components/interfaces/Settings/Logs/Logs.datePickerHelpers'
+import {
+ parseTimeRange,
+ serializeTimeRange,
+} from '@/components/interfaces/Settings/Logs/Logs.timeRange'
import type { Option } from '@/components/ui/DataTable/DataTable.types'
export const USER_PROPERTY = 'user'
@@ -129,16 +133,6 @@ export const buildColumnFilterValues = (
return wrappedByColumn
}
-export const serializeTimeRange = (range: Date[]): string =>
- range.map((date) => date.toISOString()).join(' – ')
-
-export const parseTimeRange = (value: unknown): [Date, Date] | undefined => {
- if (typeof value !== 'string') return
- const result = z.tuple([z.coerce.date(), z.coerce.date()]).safeParse(value.split(' – '))
- if (!result.success || result.data[0] > result.data[1]) return
- return result.data
-}
-
export const buildFilterGroup = (
columnFilters: { id: string; value: unknown }[],
filterableNames: Set<string>
diff --git a/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts
index 738c9426743..0a122c71b1c 100644
--- a/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts
+++ b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts
@@ -1,7 +1,11 @@
import dayjs from 'dayjs'
+import type { FilterGroup } from 'ui-patterns/FilterBar'
import { describe, expect, test } from 'vitest'
-import { filterByProjects } from '@/components/interfaces/AuditLogs/AuditLogs.utils'
+import {
+ filterByFilterGroup,
+ filterByProjects,
+} from '@/components/interfaces/AuditLogs/AuditLogs.utils'
import { filterByUsers } from '@/components/interfaces/Organization/AuditLogs/AuditLogs.utils'
import {
TIMESTAMP_MICROS_PER_MS,
@@ -101,3 +105,88 @@ describe('filterByProjects', () => {
expect(filterByProjects([logA, logB, logC], ['proj-unknown'])).toEqual([])
})
})
+
+describe('filterByFilterGroup', () => {
+ const project = (value: string) => ({
+ propertyName: 'project',
+ operator: '=',
+ value,
+ })
+ const date = {
+ propertyName: 'date',
+ operator: '=',
+ value: '2026-04-29T00:00:00.000Z – 2026-04-30T00:00:00.000Z',
+ }
+ const logs = [logA, logB, logC]
+ const requestIds = (group: FilterGroup) =>
+ filterByFilterGroup(logs, group).map((l) => l.request_id)
+
+ test('returns all logs when there are no conditions', () => {
+ expect(requestIds({ logicalOperator: 'AND', conditions: [] })).toEqual([
+ 'req-a',
+ 'req-b',
+ 'req-c',
+ ])
+ })
+
+ test('OR matches logs from any of the projects', () => {
+ expect(
+ requestIds({ logicalOperator: 'OR', conditions: [project('proj-1'), project('proj-2')] })
+ ).toEqual(['req-a', 'req-b'])
+ })
+
+ test('AND of two different projects matches nothing', () => {
+ expect(
+ requestIds({ logicalOperator: 'AND', conditions: [project('proj-1'), project('proj-2')] })
+ ).toEqual([])
+ })
+
+ test('evaluates nested groups: date AND (project A OR project B)', () => {
+ expect(
+ requestIds({
+ logicalOperator: 'AND',
+ conditions: [
+ date,
+ { logicalOperator: 'OR', conditions: [project('proj-1'), project('proj-2')] },
+ ],
+ })
+ ).toEqual(['req-a', 'req-b'])
+ })
+
+ test('ignores the date condition since the API already applies it', () => {
+ expect(requestIds({ logicalOperator: 'AND', conditions: [date] })).toEqual([
+ 'req-a',
+ 'req-b',
+ 'req-c',
+ ])
+ expect(requestIds({ logicalOperator: 'OR', conditions: [date, project('proj-1')] })).toEqual([
+ 'req-a',
+ ])
+ })
+
+ test('ignores chips that have no value yet', () => {
+ expect(requestIds({ logicalOperator: 'AND', conditions: [project('')] })).toEqual([
+ 'req-a',
+ 'req-b',
+ 'req-c',
+ ])
+ expect(
+ requestIds({ logicalOperator: 'OR', conditions: [project(''), project('proj-1')] })
+ ).toEqual(['req-a'])
+ })
+
+ test('ignores an empty nested group', () => {
+ expect(
+ requestIds({
+ logicalOperator: 'AND',
+ conditions: [project('proj-1'), { logicalOperator: 'OR', conditions: [] }],
+ })
+ ).toEqual(['req-a'])
+ })
+
+ test('excludes logs without a project_ref when a project is selected', () => {
+ expect(requestIds({ logicalOperator: 'OR', conditions: [project('proj-1')] })).not.toContain(
+ 'req-c'
+ )
+ })
+})
diff --git a/packages/ui-patterns/src/FilterBar/CommandListItem.tsx b/packages/ui-patterns/src/FilterBar/CommandListItem.tsx
index e0fd1199a5b..f0ffde4e0bd 100644
--- a/packages/ui-patterns/src/FilterBar/CommandListItem.tsx
+++ b/packages/ui-patterns/src/FilterBar/CommandListItem.tsx
@@ -31,7 +31,7 @@ export function CommandListItem({
if (!item.disabled) onSelect(item)
}}
className={cn(
- 'relative flex items-center justify-between gap-2 px-2 h-[28px] text-xs select-none outline-hidden',
+ 'relative flex items-center justify-between gap-2 px-2 h-[28px] rounded-item text-xs select-none outline-hidden',
item.disabled ? 'text-muted' : 'text-foreground cursor-pointer',
isHighlighted && 'bg-overlay-hover',
!isHighlighted && !item.disabled && 'hover:bg-surface-200'
diff --git a/packages/ui-patterns/src/FilterBar/DefaultCommandList.helpers.tsx b/packages/ui-patterns/src/FilterBar/DefaultCommandList.helpers.tsx
index dce4ee08b85..c04909f3429 100644
--- a/packages/ui-patterns/src/FilterBar/DefaultCommandList.helpers.tsx
+++ b/packages/ui-patterns/src/FilterBar/DefaultCommandList.helpers.tsx
@@ -7,5 +7,5 @@ export function GroupHeader({ label }: { label: string }) {
}
export function GroupSeparator() {
- return <div className="h-px bg-border-muted my-1" />
+ return <div className="h-px bg-border-muted -mx-1 my-1" />
}
diff --git a/packages/ui-patterns/src/FilterBar/DefaultCommandList.test.tsx b/packages/ui-patterns/src/FilterBar/DefaultCommandList.test.tsx
new file mode 100644
index 00000000000..f6854505391
--- /dev/null
+++ b/packages/ui-patterns/src/FilterBar/DefaultCommandList.test.tsx
@@ -0,0 +1,39 @@
+import { render } from '@testing-library/react'
+import { describe, expect, it } from 'vitest'
+
+import { DefaultCommandList } from './DefaultCommandList'
+import type { MenuItem } from './types'
+
+const renderList = (items: MenuItem[]) =>
+ render(<DefaultCommandList items={items} highlightedIndex={0} onSelect={() => {}} />)
+
+const getSeparators = (container: HTMLElement) => container.querySelectorAll('.h-px')
+
+describe('DefaultCommandList', () => {
+ it('renders a separator before "New 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' },
+ ])
+
+ const separators = getSeparators(container)
+ expect(separators).toHaveLength(1)
+ expect(separators[0].nextElementSibling).toBe(
+ getByText('New 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' }])
+ expect(getSeparators(container)).toHaveLength(0)
+ })
+
+ it('does not render a separator when there is no "New Group" item', () => {
+ const { container } = renderList([
+ { value: 'project', label: 'Project' },
+ { value: 'date', label: 'Date range' },
+ ])
+ expect(getSeparators(container)).toHaveLength(0)
+ })
+})
diff --git a/packages/ui-patterns/src/FilterBar/DefaultCommandList.tsx b/packages/ui-patterns/src/FilterBar/DefaultCommandList.tsx
index a84e996a17a..f7ead4ec181 100644
--- a/packages/ui-patterns/src/FilterBar/DefaultCommandList.tsx
+++ b/packages/ui-patterns/src/FilterBar/DefaultCommandList.tsx
@@ -1,6 +1,6 @@
'use client'
-import { useEffect, useMemo, useRef } from 'react'
+import { Fragment, useEffect, useMemo, useRef } from 'react'
import { CommandListItem } from './CommandListItem'
import { EmptyState, GroupHeader, GroupSeparator } from './DefaultCommandList.helpers'
@@ -59,30 +59,32 @@ export function DefaultCommandList({
if (items.length === 0) {
return (
- <div ref={listRef} className="max-h-[300px] overflow-y-auto py-1">
+ <div ref={listRef} className="max-h-[300px] overflow-y-auto p-1">
<EmptyState />
</div>
)
}
return (
- <div ref={listRef} className="max-h-[300px] overflow-y-auto py-1">
+ <div ref={listRef} className="max-h-[300px] overflow-y-auto p-1">
{groups.map((groupData, groupIndex) => (
<div key={groupData.group}>
{groupIndex > 0 && showGroupHeaders && <GroupSeparator />}
{showGroupHeaders && groupData.group && (
<GroupHeader label={OPERATOR_GROUP_LABELS[groupData.group]} />
)}
- {groupData.items.map(({ item, index }) => (
- <CommandListItem
- showSelection={showSelection}
- key={`${item.value}-${item.label}`}
- item={item}
- isHighlighted={index === highlightedIndex}
- includeIcon={includeIcon}
- onSelect={onSelect}
- setRef={setItemRef(index)}
- />
+ {groupData.items.map(({ item, index }, itemIndex) => (
+ <Fragment key={`${item.value}-${item.label}`}>
+ {item.value === '__new_group__' && itemIndex > 0 && <GroupSeparator />}
+ <CommandListItem
+ showSelection={showSelection}
+ item={item}
+ isHighlighted={index === highlightedIndex}
+ includeIcon={includeIcon}
+ onSelect={onSelect}
+ setRef={setItemRef(index)}
+ />
+ </Fragment>
))}
</div>
))}
diff --git a/packages/ui-patterns/src/FilterBar/FilterBar.tsx b/packages/ui-patterns/src/FilterBar/FilterBar.tsx
index 5bc4791b30c..33616d2af94 100644
--- a/packages/ui-patterns/src/FilterBar/FilterBar.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterBar.tsx
@@ -22,6 +22,8 @@ export type FilterBarProps = {
isLoading?: boolean
className?: string
supportsOperators?: boolean
+ /** Logical operator for groups created via "New Group". Defaults to 'AND'. */
+ defaultGroupOperator?: FilterGroupType['logicalOperator']
variant?: FilterBarVariant
icon?: React.ReactNode
/**
@@ -141,6 +143,7 @@ export const FilterBar = forwardRef<FilterBarHandle, FilterBarProps>(function Fi
isLoading,
className,
supportsOperators = false,
+ defaultGroupOperator,
variant = 'default',
icon,
freeformDefaultProperty,
@@ -159,6 +162,7 @@ export const FilterBar = forwardRef<FilterBarHandle, FilterBarProps>(function Fi
actions={actions}
isLoading={isLoading}
supportsOperators={supportsOperators}
+ defaultGroupOperator={defaultGroupOperator}
variant={variant}
icon={icon}
freeformDefaultProperty={freeformDefaultProperty}
diff --git a/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx b/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx
index 7effeb09317..d6b01935422 100644
--- a/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx
@@ -98,6 +98,8 @@ export type FilterBarRootProps = {
actions?: FilterBarAction[]
isLoading?: boolean
supportsOperators?: boolean
+ /** Logical operator for groups created via "New Group". Defaults to 'AND'. */
+ defaultGroupOperator?: FilterGroup['logicalOperator']
variant?: FilterBarVariant
icon?: React.ReactNode
freeformDefaultProperty?: string
@@ -121,6 +123,7 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
actions,
isLoading: externalLoading,
supportsOperators = false,
+ defaultGroupOperator,
variant = 'default',
icon,
freeformDefaultProperty,
@@ -205,6 +208,7 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
handleOperatorChange,
newPathRef,
setIsCommandMenuVisible,
+ defaultGroupOperator,
})
const { handleKeyDown } = useKeyboardNavigation({
diff --git a/packages/ui-patterns/src/FilterBar/useCommandHandling.ts b/packages/ui-patterns/src/FilterBar/useCommandHandling.ts
index 2adbce682ac..94e05f3aba8 100644
--- a/packages/ui-patterns/src/FilterBar/useCommandHandling.ts
+++ b/packages/ui-patterns/src/FilterBar/useCommandHandling.ts
@@ -22,6 +22,7 @@ export function useCommandHandling({
handleOperatorChange,
newPathRef,
setIsCommandMenuVisible,
+ defaultGroupOperator,
}: {
activeInput: ActiveInputState
setActiveInput: (input: ActiveInputState) => void
@@ -34,6 +35,7 @@ export function useCommandHandling({
handleOperatorChange: (path: number[], value: string) => void
newPathRef: React.MutableRefObject<number[]>
setIsCommandMenuVisible: (visible: boolean) => void
+ defaultGroupOperator?: FilterGroup['logicalOperator']
}) {
const handleGroupCommand = useCallback(() => {
if (activeInput && activeInput.type === 'group') {
@@ -43,7 +45,7 @@ export function useCommandHandling({
// Group-add is structural (no value typed yet), so update draft state only — onApply will
// fire once a value gets committed inside the new group.
- const updatedFilters = addGroupToGroup(activeFilters, currentPath)
+ const updatedFilters = addGroupToGroup(activeFilters, currentPath, defaultGroupOperator)
onFilterChange(updatedFilters)
newPathRef.current = [...currentPath, group.conditions.length]
setTimeout(() => {
@@ -51,7 +53,15 @@ export function useCommandHandling({
}, 0)
onFreeformTextChange('')
}
- }, [activeInput, activeFilters, onFilterChange, newPathRef, setActiveInput, onFreeformTextChange])
+ }, [
+ activeInput,
+ activeFilters,
+ onFilterChange,
+ newPathRef,
+ setActiveInput,
+ onFreeformTextChange,
+ defaultGroupOperator,
+ ])
const handleValueCommand = useCallback(
(item: MenuItem) => {
diff --git a/packages/ui-patterns/src/FilterBar/utils.test.ts b/packages/ui-patterns/src/FilterBar/utils.test.ts
index cafa8ac2014..0e620282747 100644
--- a/packages/ui-patterns/src/FilterBar/utils.test.ts
+++ b/packages/ui-patterns/src/FilterBar/utils.test.ts
@@ -135,6 +135,23 @@ describe('FilterBar Utils', () => {
conditions: [],
})
})
+
+ it('uses the given logical operator for the new group', () => {
+ const result = addGroupToGroup(sampleFilterGroup, [], 'OR')
+ expect(result.conditions[2]).toEqual({ logicalOperator: 'OR', conditions: [] })
+ })
+
+ it('uses the given logical operator for a nested new group', () => {
+ const nested = {
+ logicalOperator: 'AND' as const,
+ conditions: [{ logicalOperator: 'AND' as const, conditions: [] }],
+ }
+ const result = addGroupToGroup(nested, [0], 'OR')
+ expect((result.conditions[0] as typeof nested).conditions[0]).toEqual({
+ logicalOperator: 'OR',
+ conditions: [],
+ })
+ })
})
describe('removeFromGroup', () => {
diff --git a/packages/ui-patterns/src/FilterBar/utils.ts b/packages/ui-patterns/src/FilterBar/utils.ts
index be7e9769396..63f2f8dd9a2 100644
--- a/packages/ui-patterns/src/FilterBar/utils.ts
+++ b/packages/ui-patterns/src/FilterBar/utils.ts
@@ -166,11 +166,15 @@ export function addFilterToGroup(
}
}
-export function addGroupToGroup(group: FilterGroup, path: number[]): FilterGroup {
+export function addGroupToGroup(
+ group: FilterGroup,
+ path: number[],
+ logicalOperator: FilterGroup['logicalOperator'] = 'AND'
+): FilterGroup {
if (path.length === 0) {
return {
...group,
- conditions: [...group.conditions, { logicalOperator: 'AND', conditions: [] }],
+ conditions: [...group.conditions, { logicalOperator, conditions: [] }],
}
}
@@ -178,7 +182,7 @@ export function addGroupToGroup(group: FilterGroup, path: number[]): FilterGroup
return {
...group,
conditions: group.conditions.map((condition, i) =>
- i === current ? addGroupToGroup(condition as FilterGroup, rest) : condition
+ i === current ? addGroupToGroup(condition as FilterGroup, rest, logicalOperator) : condition
),
}
}