Skip to content

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

Joshen/debug 97 use the same filter bar in unified logs and table editor (#46071)

Joshen Lim7728bfae1d97
diff --git a/apps/studio/components/grid/components/header/filter/FilterPopoverNew.tsx b/apps/studio/components/grid/components/header/filter/FilterPopoverNew.tsx
index 5bc651844ec..02ba36a0a75 100644
--- a/apps/studio/components/grid/components/header/filter/FilterPopoverNew.tsx
+++ b/apps/studio/components/grid/components/header/filter/FilterPopoverNew.tsx
@@ -1,6 +1,6 @@
import { format } from 'date-fns'
import { Loader2 } from 'lucide-react'
-import { useCallback, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { AiIconAnimation, Button, Calendar } from 'ui'
import {
CustomOptionProps,
@@ -18,6 +18,7 @@ import { columnToFilterProperty } from './FilterPopoverNew.utils'
import { useTableFilter } from '@/components/grid/hooks/useTableFilter'
import type { Filter } from '@/components/grid/types'
import { useSqlFilterGenerateMutation } from '@/data/ai/sql-filter-mutation'
+import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
import { useTableEditorTableStateSnapshot } from '@/state/table-editor-table'
export interface FilterPopoverProps {
@@ -133,8 +134,17 @@ export const FilterPopoverNew = ({
const [freeformText, setFreeformText] = useState('')
const { mutateAsync: generateFilters, isPending: isGenerating } = useSqlFilterGenerateMutation()
- // Convert filters to FilterGroup for the FilterBar
- const filterGroup = useMemo(() => filtersToFilterGroup(filters), [filters])
+ // Local state for the FilterBar — committed to the table state on apply only,
+ // so transient edits don't fire data requests.
+ const [filterGroup, setFilterGroup] = useState<FilterGroup>(() => filtersToFilterGroup(filters))
+
+ const syncFromFilters = useStaticEffectEvent(() => {
+ setFilterGroup(filtersToFilterGroup(filters))
+ })
+
+ useEffect(() => {
+ syncFromFilters()
+ }, [filters, syncFromFilters])
const columns = useMemo(() => snap.table?.columns ?? [], [snap.table?.columns])
@@ -164,18 +174,21 @@ export const FilterPopoverNew = ({
[filterProperties]
)
- // Handle filter changes from FilterBar
- const handleFilterChange = useCallback(
- (newFilterGroup: FilterGroup) => {
- const newFilters = filterGroupToFilters(newFilterGroup)
- const conditionRemoved = newFilters.length < filters.length
- setFilters(newFilters)
-
- if (conditionRemoved) {
+ // Transient edits stay local — onApply pushes to the table state.
+ const handleFilterChange = useCallback((newFilterGroup: FilterGroup) => {
+ setFilterGroup((prev) => {
+ if (newFilterGroup.conditions.length < prev.conditions.length) {
setTimeout(() => filterBarRef.current?.focus(), 0)
}
+ return newFilterGroup
+ })
+ }, [])
+
+ const handleApply = useCallback(
+ (newFilterGroup: FilterGroup) => {
+ setFilters(filterGroupToFilters(newFilterGroup))
},
- [filters.length, setFilters]
+ [setFilters]
)
const actions = useMemo(
@@ -218,6 +231,7 @@ export const FilterPopoverNew = ({
filterProperties={filterProperties}
filters={filterGroup}
onFilterChange={handleFilterChange}
+ onApply={handleApply}
freeformText={freeformText}
onFreeformTextChange={setFreeformText}
actions={actions}
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
index d9adfd120e3..ae1abc01f5b 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
@@ -24,15 +24,13 @@ import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
useIsMobile,
} from 'ui'
import { RefreshButton } from '../../ui/DataTable/RefreshButton'
import { generateDynamicColumns, UNIFIED_LOGS_COLUMNS } from './components/Columns'
import { DownloadLogsButton } from './components/DownloadLogsButton'
+import { LogsFilterBar } from './components/LogsFilterBar'
import { LogsListPanel } from './components/LogsListPanel'
import { TooltipLabel } from './components/TooltipLabel'
import { ServiceFlowPanel } from './ServiceFlowPanel'
@@ -45,16 +43,15 @@ import { getFacetedUniqueValues, getLevelRowClassName } from './UnifiedLogs.util
import { LEVELS } from '@/components/ui/DataTable/DataTable.constants'
import { Option } from '@/components/ui/DataTable/DataTable.types'
import { arrSome, inDateRange } from '@/components/ui/DataTable/DataTable.utils'
-import { DataTableFilterCommand } from '@/components/ui/DataTable/DataTableFilters/DataTableFilterCommand'
import { DataTableFilterControlsDrawer } from '@/components/ui/DataTable/DataTableFilters/DataTableFilterControlsDrawer'
import { DataTableInfinite } from '@/components/ui/DataTable/DataTableInfinite'
import { DataTableSideBarLayout } from '@/components/ui/DataTable/DataTableSideBarLayout'
import { DataTableViewOptions } from '@/components/ui/DataTable/DataTableViewOptions'
import { FilterSideBar } from '@/components/ui/DataTable/FilterSideBar'
import { LiveButton } from '@/components/ui/DataTable/LiveButton'
-import { Kbd } from '@/components/ui/DataTable/primitives/Kbd'
import { DataTableProvider } from '@/components/ui/DataTable/providers/DataTableProvider'
import { TimelineChart } from '@/components/ui/DataTable/TimelineChart'
+import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'
import { useUnifiedLogsChartQuery } from '@/data/logs/unified-logs-chart-query'
import { useUnifiedLogsCountQuery } from '@/data/logs/unified-logs-count-query'
import { useUnifiedLogsInfiniteQuery } from '@/data/logs/unified-logs-infinite-query'
@@ -387,38 +384,29 @@ export const UnifiedLogs = () => {
id="panel-right"
className="flex max-w-full flex-1 flex-col overflow-hidden"
>
- <div ref={topBarRef} className="top-0 z-10 flex flex-col gap-2 bg-background pb-3">
- <div className="flex flex-wrap items-center gap-2 px-2 pt-2.5 pb-0.5">
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- size="tiny"
- type="text"
- icon={isFilterBarOpen ? <PanelLeftClose /> : <PanelLeftOpen />}
- onClick={() => setIsFilterBarOpen((prev) => !prev)}
- className="hidden w-[26px] sm:flex"
- aria-label={isFilterBarOpen ? 'Hide filters' : 'Show filters'}
- />
- </TooltipTrigger>
- <TooltipContent side="bottom">
- <p>
- Toggle controls with{' '}
- <Kbd className="ml-1 text-muted-foreground group-hover:text-accent-foreground">
- <span className="mr-1">⌘</span>
- <span>B</span>
- </Kbd>
- </p>
- </TooltipContent>
- </Tooltip>
- <div className="order-first w-full min-w-0 sm:order-0 sm:w-auto sm:flex-1 **:[[cmdk-input-wrapper]]:px-3! [&_button]:px-3! [&_button>span]:h-[26px]! [&_button>span]:py-0! [&_input]:h-[26px]! [&_input]:py-0!">
- <DataTableFilterCommand
- placeholder="Search logs..."
- searchParamsParser={SEARCH_PARAMS_PARSER}
+ <div ref={topBarRef} className="top-0 z-10 flex flex-col bg-background">
+ <div className="flex flex-wrap items-center gap-2 px-2 border-b">
+ <ShortcutTooltip shortcutId={SHORTCUT_IDS.DATA_TABLE_TOGGLE_FILTERS} side="bottom">
+ <Button
+ size="tiny"
+ type="text"
+ icon={isFilterBarOpen ? <PanelLeftClose /> : <PanelLeftOpen />}
+ onClick={() => setIsFilterBarOpen((prev) => !prev)}
+ className="hidden w-[26px] sm:flex"
+ aria-label={isFilterBarOpen ? 'Hide filters' : 'Show filters'}
/>
+ </ShortcutTooltip>
+
+ <div className="h-full border-r" />
+
+ <div className="order-first w-full min-w-0 sm:order-0 sm:w-auto sm:flex-1 py-2">
+ <LogsFilterBar />
</div>
+
<div className="block sm:hidden">
<DataTableFilterControlsDrawer />
</div>
+
<div className="ml-auto flex items-center gap-x-2">
<RefreshButton isLoading={isRefetchingData} onRefresh={refetchAllData} />
<DataTableViewOptions />
@@ -431,10 +419,11 @@ export const UnifiedLogs = () => {
) : null}
</div>
</div>
+
<TimelineChart
data={unifiedLogsChart}
className={cn(
- '-mb-2',
+ '-mb-1.5 mt-1.5',
isFetchingCharts && 'opacity-60 transition-opacity duration-150'
)}
columnId="timestamp"
@@ -458,11 +447,10 @@ export const UnifiedLogs = () => {
<div
className={cn(
'h-full [&>div]:h-full',
- '[&_thead_tr]:bg-[linear-gradient(to_bottom,hsl(var(--background-default)),hsl(var(--background-surface-75)))]!',
'[&_thead_th]:[border-top:none]! [&_thead_th]:[border-bottom:none]!',
'[&_thead_th]:[box-shadow:inset_0_-1px_0_hsl(var(--border-default))]!',
- '[&_thead_tr]:border-b-0! [&_tbody_tr]:border-b-0! [&_thead_tr:hover]:bg-[linear-gradient(to_bottom,hsl(var(--background-default)),hsl(var(--background-surface-75)))]!',
- '[&_thead_th]:text-foreground-lighter!'
+ '[&_thead_th]:text-foreground-lighter! [&_thead_tr:hover]:bg-surface-75',
+ '[&_thead_tr]:border-b-0! [&_tbody_tr]:border-b-0!'
)}
>
<DataTableInfinite
diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/DownloadLogsButton.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/DownloadLogsButton.tsx
index 121ecba4471..8237604a7eb 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/components/DownloadLogsButton.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/components/DownloadLogsButton.tsx
@@ -94,7 +94,7 @@ export const DownloadLogsButton = ({ searchParameters }: DownloadLogsButtonProps
return (
<>
<DropdownMenu>
- <DropdownMenuTrigger>
+ <DropdownMenuTrigger asChild>
<ButtonTooltip
type="default"
className="w-[26px]"
diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx
new file mode 100644
index 00000000000..d8d4d681033
--- /dev/null
+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.tsx
@@ -0,0 +1,105 @@
+import { groupBy } from 'lodash'
+import { LoaderCircle, Search } from 'lucide-react'
+import { useEffect, useState } from 'react'
+import { FilterBar, FilterCondition, type FilterGroup, type FilterProperty } from 'ui-patterns'
+
+import { useDataTable } from '@/components/ui/DataTable/providers/DataTableProvider'
+import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
+
+const buildFilterGroup = (
+ columnFilters: { id: string; value: unknown }[],
+ filterableNames: Set<string>
+): FilterGroup => {
+ const conditions: FilterCondition[] = []
+ for (const { id, value } of columnFilters) {
+ if (!filterableNames.has(id) || value === null || value === undefined) continue
+ const values = Array.isArray(value) ? value : [value]
+ for (const v of values) {
+ conditions.push({
+ propertyName: id,
+ value: v as FilterCondition['value'],
+ operator: '=',
+ })
+ }
+ }
+ return { logicalOperator: 'AND', conditions }
+}
+
+export const LogsFilterBar = () => {
+ const { table, filterFields, columnFilters, isFetching } = useDataTable()
+
+ const [freeformText, setFreeformText] = useState('')
+
+ const filterProperties: FilterProperty[] = filterFields
+ .filter((x) => x.type !== 'timerange')
+ .map((filter) => ({
+ label: filter.label,
+ name: filter.value,
+ type: 'string',
+ options: filter.options ?? [],
+ operators: ['='],
+ }))
+
+ // Local state because the FilterBar carries transient states
+ const [filters, setFilters] = useState<FilterGroup>(() =>
+ buildFilterGroup(columnFilters, new Set(filterProperties.map((p) => p.name)))
+ )
+
+ // Read latest filterProperties without making the effect depend on its (per-render) identity.
+ const syncFromColumnFilters = useStaticEffectEvent(() => {
+ setFilters(buildFilterGroup(columnFilters, new Set(filterProperties.map((p) => p.name))))
+ })
+
+ // No nested conditions in unified logs — type-cast to FilterCondition on read.
+ const onApply = (next: FilterGroup) => {
+ const isValid = next.conditions.every(
+ (x) =>
+ !!(x as FilterCondition).operator &&
+ !!(x as FilterCondition).value &&
+ !!(x as FilterCondition).propertyName
+ )
+ if (!isValid) return
+
+ const filterConditions = next.conditions as FilterCondition[]
+ const groupedFilterConditions = groupBy(filterConditions, 'propertyName')
+ Object.entries(groupedFilterConditions).forEach(([name, conditions]) => {
+ table.getColumn(name)?.setFilterValue(conditions.map((x) => x.value))
+ })
+
+ // Only clear filters owned by this bar — leaves externally-set filters
+ // (e.g. the timeline date range) untouched.
+ const managedNames = new Set(filterProperties.map((p) => p.name))
+ const nextNames = new Set(Object.keys(groupedFilterConditions))
+ const filtersToRemove = table
+ .getState()
+ .columnFilters.filter((x) => managedNames.has(x.id) && !nextNames.has(x.id))
+ filtersToRemove.forEach((x) => {
+ table.getColumn(x.id)?.setFilterValue(undefined)
+ })
+ }
+
+ useEffect(() => {
+ syncFromColumnFilters()
+ }, [columnFilters, syncFromColumnFilters])
+
+ return (
+ <FilterBar
+ variant="pill"
+ className="bg-transparent border-0 [&>div>div>div>input]:!text-xs"
+ filterProperties={filterProperties}
+ freeformText={freeformText}
+ filters={filters}
+ onFilterChange={setFilters}
+ onApply={onApply}
+ onFreeformTextChange={setFreeformText}
+ isLoading={isFetching}
+ icon={
+ isFetching ? (
+ <LoaderCircle className="h-4 w-4 animate-spin text-foreground-muted opacity-50" />
+ ) : (
+ <Search className="text-foreground-muted w-4 h-4 sticky" />
+ )
+ }
+ />
+ )
+}
diff --git a/apps/studio/components/ui/DataTable/DataTable.types.ts b/apps/studio/components/ui/DataTable/DataTable.types.ts
index d147394feaf..7354550ed97 100644
--- a/apps/studio/components/ui/DataTable/DataTable.types.ts
+++ b/apps/studio/components/ui/DataTable/DataTable.types.ts
@@ -3,7 +3,7 @@ import type { ReactNode } from 'react'
// TODO: we could type the value(!) especially when using enums
export type Option = {
label: string
- value: string | boolean | number | undefined
+ value: string
}
export type DatePreset = {
diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCommand.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCommand.tsx
deleted file mode 100644
index 75c56eb5c76..00000000000
--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCommand.tsx
+++ /dev/null
@@ -1,407 +0,0 @@
-import { formatDistanceToNow } from 'date-fns'
-import { LoaderCircle, Search, X } from 'lucide-react'
-import { ParserBuilder } from 'nuqs'
-import { useEffect, useMemo, useRef, useState } from 'react'
-import {
- cn,
- Command_Shadcn_ as Command,
- CommandEmpty_Shadcn_ as CommandEmpty,
- CommandGroup_Shadcn_ as CommandGroup,
- CommandInput_Shadcn_ as CommandInput,
- CommandItem_Shadcn_ as CommandItem,
- CommandList_Shadcn_ as CommandList,
- CommandSeparator_Shadcn_ as CommandSeparator,
- Separator,
-} from 'ui'
-
-import type { DataTableFilterField } from '../DataTable.types'
-import { formatCompactNumber } from '../DataTable.utils'
-import { Kbd } from '../primitives/Kbd'
-import { useDataTable } from '../providers/DataTableProvider'
-import {
- columnFiltersParser,
- getFieldOptions,
- getFilterValue,
- getWordByCaretPosition,
- replaceInputByFieldType,
-} from './DataTableFilters.utils'
-import { useLocalStorage } from '@/hooks/misc/useLocalStorage'
-
-// FIXME: there is an issue on cmdk if I wanna only set a single slider value...
-
-interface DataTableFilterCommandProps {
- // TODO: maybe use generics for the parser
- searchParamsParser: Record<string, ParserBuilder<any>>
- placeholder?: string
-}
-
-export function DataTableFilterCommand({
- searchParamsParser,
- placeholder = 'Search data table...',
-}: DataTableFilterCommandProps) {
- const { table, isFetching, filterFields: _filterFields, getFacetedUniqueValues } = useDataTable()
- const columnFilters = table.getState().columnFilters
- const inputRef = useRef<HTMLInputElement>(null)
- const [open, setOpen] = useState<boolean>(false)
- const [currentWord, setCurrentWord] = useState<string>('')
- const filterFields = useMemo(
- () => _filterFields?.filter((i) => !i.commandDisabled),
- [_filterFields]
- )
- const columnParser = useMemo(
- () => columnFiltersParser({ searchParamsParser, filterFields }),
- [searchParamsParser, filterFields]
- )
- const [inputValue, setInputValue] = useState<string>(columnParser.serialize(columnFilters))
- const [lastSearches, setLastSearches] = useLocalStorage<
- {
- search: string
- timestamp: number
- }[]
- >('data-table-command', [])
-
- const trimmedInputValue = inputValue.trim()
-
- const queryFields = filterFields.filter(
- (x) => typeof x.value === 'string' && currentWord.includes(`${x.value}:`)
- )
-
- useEffect(() => {
- // TODO: we could check for ARRAY_DELIMITER or SLIDER_DELIMITER to auto-set filter when typing
- if (currentWord !== '' && open) return
- // reset
- if (currentWord !== '' && !open) setCurrentWord('')
- // avoid recursion
- if (trimmedInputValue === '' && !open) return
-
- const searchParams = columnParser.parse(inputValue)
-
- const currentFilters = table.getState().columnFilters
- const currentEnabledFilters = currentFilters.filter((filter) => {
- const field = _filterFields?.find((field) => field.value === filter.id)
- return !field?.commandDisabled
- })
-
- for (const key of Object.keys(searchParams)) {
- const value = searchParams[key as keyof typeof searchParams]
- table.getColumn(key)?.setFilterValue(value)
- }
- const currentFiltersToReset = currentEnabledFilters.filter((filter) => {
- return !(filter.id in searchParams)
- })
- for (const filter of currentFiltersToReset) {
- table.getColumn(filter.id)?.setFilterValue(undefined)
- }
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [inputValue, open, currentWord])
-
- useEffect(() => {
- // REMINDER: only update the input value if the command is closed (avoids jumps while open)
- if (!open) {
- setInputValue(columnParser.serialize(columnFilters))
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [columnFilters, filterFields, open])
-
- useEffect(() => {
- if (open) {
- inputRef?.current?.focus()
- }
- }, [open])
-
- return (
- <div>
- <button
- type="button"
- className={cn(
- 'group flex w-full items-center rounded-lg border border-input bg-background px-3 text-muted-foreground ring-offset-background focus-within:outline-hidden focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 hover:bg-accent/50 hover:text-accent-foreground',
- open ? 'hidden' : 'visible'
- )}
- onClick={() => setOpen(true)}
- >
- {isFetching ? (
- <LoaderCircle className="mr-2 h-4 w-4 shrink-0 animate-spin text-muted-foreground opacity-50 group-hover:text-popover-foreground" />
- ) : (
- <Search className="mr-2 h-4 w-4 shrink-0 text-muted-foreground opacity-50 group-hover:text-popover-foreground" />
- )}
- <span
- className={cn(
- 'h-9 w-full max-w-sm truncate py-3 text-left text-xs outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
- 'flex items-center md:max-w-xl lg:max-w-4xl xl:max-w-5xl',
- trimmedInputValue ? 'text-foreground' : 'text-foreground-light'
- )}
- >
- {trimmedInputValue ? inputValue : placeholder}
- </span>
- {/* [Joshen] Temporarily disabling as this conflicts with existing CMD K shortcut */}
- {/* <Kbd className="ml-auto text-muted-foreground group-hover:text-accent-foreground">
- <span className="mr-1">⌘</span>
- <span>K</span>
- </Kbd> */}
- </button>
-
- <Command
- className={cn(
- 'overflow-visible rounded-lg border border-border shadow-md [&>div]:border-none bg',
- open ? 'visible' : 'hidden'
- )}
- filter={(value, search, keywords) =>
- getFilterValue({ value, search, keywords, currentWord })
- }
- onKeyDown={(e) => {
- // Stop arrow key navigation from propagating to parent components
- if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
- e.stopPropagation()
- }
- }}
- >
- <CommandInput
- ref={inputRef}
- value={inputValue}
- onValueChange={setInputValue}
- onKeyDown={(e) => {
- if (e.key === 'Escape') inputRef?.current?.blur()
- }}
- onBlur={() => {
- setOpen(false)
- // FIXME: doesnt reflect the jumps
- // FIXME: will save non-existing searches
- // TODO: extract into function
- const search = inputValue.trim()
- if (!search) return
- const timestamp = Date.now()
- const searchIndex = lastSearches.findIndex((item) => item.search === search)
- if (searchIndex !== -1) {
- lastSearches[searchIndex].timestamp = timestamp
- setLastSearches(lastSearches)
- return
- }
- setLastSearches([...lastSearches, { search, timestamp }])
- return
- }}
- onInput={(e) => {
- const caretPosition = e.currentTarget?.selectionStart || -1
- const value = e.currentTarget?.value || ''
- const word = getWordByCaretPosition({ value, caretPosition })
- setCurrentWord(word)
- }}
- placeholder={placeholder}
- className="text-xs text-foreground"
- />
- <div className="relative">
- <div className="absolute top-2 z-50 w-full overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-md outline-hidden animate-in">
- {/* default height is 300px but in case of more, we'd like to tease the user */}
- <CommandList className="max-h-[310px] bg-surface-100">
- <CommandEmpty>No results found.</CommandEmpty>
- <CommandGroup heading="Filter">
- {filterFields.map((field) => {
- if (typeof field.value !== 'string') return null
- if (inputValue.includes(`${field.value}:`)) return null
- // TBD: should we handle this in the component?
- return (
- <CommandItem
- key={field.value}
- value={field.value}
- onMouseDown={(e) => {
- e.preventDefault()
- e.stopPropagation()
- }}
- onSelect={(value) => {
- setInputValue((prev) => {
- if (currentWord.trim() === '') {
- const input = `${prev}${value}`
- return `${input}:`
- }
- // lots of cheat
- const isStarting = currentWord === prev
- const prefix = isStarting ? '' : ' '
- const input = prev.replace(`${prefix}${currentWord}`, `${prefix}${value}`)
- return `${input}:`
- })
- setCurrentWord(`${value}:`)
- }}
- className="group"
- >
- {field.label}
- <CommandItemSuggestions field={field} />
- </CommandItem>
- )
- })}
- </CommandGroup>
-
- <CommandSeparator />
-
- {queryFields.length > 0 && (
- <>
- <CommandGroup heading="Query">
- {queryFields.map((field) => {
- const column = table.getColumn(field.value)
- const facetedValue =
- getFacetedUniqueValues?.(table, field.value) ||
- column?.getFacetedUniqueValues()
-
- const options = getFieldOptions({ field })
-
- return options.map((optionValue) => {
- return (
- <CommandItem
- key={`${String(field.value)}:${optionValue}`}
- value={`${String(field.value)}:${optionValue}`}
- onMouseDown={(e) => {
- e.preventDefault()
- e.stopPropagation()
- }}
- onSelect={(value) => {
- setInputValue((prev) =>
- replaceInputByFieldType({
- prev,
- currentWord,
- optionValue,
- value,
- field,
- })
- )
- setCurrentWord('')
- }}
- >
- {`${optionValue}`}
- {facetedValue?.has(optionValue) ? (
- <span className="ml-auto font-mono text-muted-foreground">
- {formatCompactNumber(facetedValue.get(optionValue) || 0)}
- </span>
- ) : null}
- </CommandItem>
- )
- })
- })}
- </CommandGroup>
- <CommandSeparator />
- </>
- )}
-
- {lastSearches.length > 0 && (
- <CommandGroup heading="Suggestions">
- {lastSearches
- .sort((a, b) => b.timestamp - a.timestamp)
- .slice(0, 5)
- .map((item) => {
- return (
- <CommandItem
- key={`suggestion:${item.search}`}
- value={`suggestion:${item.search}`}
- onMouseDown={(e) => {
- e.preventDefault()
- e.stopPropagation()
- }}
- onSelect={(value) => {
- const search = value.replace('suggestion:', '')
- setInputValue(`${search} `)
- setCurrentWord('')
- }}
- className="group"
- >
- {item.search}
- <span className="ml-auto truncate text-muted-foreground/80 group-aria-selected:block">
- {formatDistanceToNow(item.timestamp, {
- addSuffix: true,
- })}
- </span>
- <button
- type="button"
- onMouseDown={(e) => {
- e.preventDefault()
- e.stopPropagation()
- }}
- onClick={(e) => {
- e.preventDefault()
- e.stopPropagation()
- // TODO: extract into function
- setLastSearches(lastSearches.filter((i) => i.search !== item.search))
- }}
- className="ml-1 hidden rounded-md p-0.5 hover:bg-background group-aria-selected:block"
- >
- <X className="h-4 w-4" />
- </button>
- </CommandItem>
- )
- })}
- </CommandGroup>
- )}
- </CommandList>
-
- <div className="bg-surface-100 flex flex-wrap justify-between gap-3 border-t bg-accent/50 px-2 py-1.5 text-sm text-accent-foreground">
- <div className="flex flex-wrap gap-3">
- <span>
- Use <Kbd>↑</Kbd> <Kbd>↓</Kbd> to navigate
- </span>
- <span>
- <Kbd>Enter</Kbd> to query
- </span>
- <span>
- <Kbd>Esc</Kbd> to close
- </span>
- <Separator orientation="vertical" className="my-auto h-3" />
- <span>
- Union: <Kbd>regions:a,b</Kbd>
- </span>
- <span>
- Range: <Kbd>p95:59-340</Kbd>
- </span>
- </div>
- {lastSearches.length ? (
- <button
- type="button"
- className="text-muted-foreground hover:text-accent-foreground"
- onMouseDown={(e) => {
- e.preventDefault()
- e.stopPropagation()
- }}
- onClick={() => setLastSearches([])}
- >
- Clear suggestions
- </button>
- ) : null}
- </div>
- </div>
- </div>
- </Command>
- </div>
- )
-}
-
-function CommandItemSuggestions<TData>({ field }: { field: DataTableFilterField<TData> }) {
- const { table, getFacetedMinMaxValues, getFacetedUniqueValues } = useDataTable()
- const value = field.value as string
- const className = 'ml-2 hidden truncate text-foreground-lighter group-aria-selected:block'
-
- switch (field.type) {
- case 'checkbox': {
- return (
- <span className={cn(className)}>
- {field.options && field.options.length > 0
- ? field.options.map(({ value }) => `[${value}]`).join(' ')
- : getFacetedUniqueValues
- ? Array.from(getFacetedUniqueValues(table, value)?.keys() || [])
- .map((value) => `[${value}]`)
- .join(' ')
- : null}
- </span>
- )
- }
- case 'slider': {
- const [min, max] = getFacetedMinMaxValues?.(table, value) || [field.min, field.max]
- return (
- <span className={cn(className)}>
- [{min} - {max}]
- </span>
- )
- }
- case 'input': {
- return <span className={cn(className)}>[{`${String(field.value)}`} input]</span>
- }
- default: {
- return null
- }
- }
-}
diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx
index 601369a89ad..e113d5161e1 100644
--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx
@@ -39,14 +39,14 @@ export function DataTableFilterControls({
const value = field.value as string
return (
<AccordionItem key={value} value={value} className="border-none">
- <AccordionTrigger className="w-full px-2 py-0 hover:no-underline data-[state=closed]:text-muted-foreground data-open:text-foreground focus-within:data-closed:text-foreground hover:data-closed:text-foreground">
- <div className="flex w-full items-center justify-between gap-2 truncate py-2 pr-2">
- <div className="flex items-center gap-2 truncate">
+ <div className="flex items-center gap-2 pr-2">
+ <AccordionTrigger className="flex-1 px-2 py-0 hover:no-underline data-[state=closed]:text-muted-foreground data-open:text-foreground focus-within:data-closed:text-foreground hover:data-closed:text-foreground">
+ <div className="flex items-center gap-2 truncate py-2">
<p className="text-sm">{field.label}</p>
</div>
- <DataTableFilterResetButton {...field} />
- </div>
- </AccordionTrigger>
+ </AccordionTrigger>
+ <DataTableFilterResetButton {...field} />
+ </div>
<AccordionContent>
{/* REMINDER: avoid the focus state to be cut due to overflow-hidden */}
{/* REMINDER: need to move within here because of accordion height animation */}
diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilters.utils.ts b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilters.utils.ts
deleted file mode 100644
index 45eacf19427..00000000000
--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilters.utils.ts
+++ /dev/null
@@ -1,256 +0,0 @@
-import { ColumnFiltersState } from '@tanstack/react-table'
-import { ParserBuilder } from 'nuqs'
-
-import { ARRAY_DELIMITER, RANGE_DELIMITER, SLIDER_DELIMITER } from '../DataTable.constants'
-import type { DataTableFilterField } from '../DataTable.types'
-import { isArrayOfDates } from '../DataTable.utils'
-
-/**
- * Extracts the word from the given string at the specified caret position.
- */
-export function getWordByCaretPosition({
- value,
- caretPosition,
-}: {
- value: string
- caretPosition: number
-}) {
- let start = caretPosition
- let end = caretPosition
-
- while (start > 0 && value[start - 1] !== ' ') start--
- while (end < value.length && value[end] !== ' ') end++
-
- const word = value.substring(start, end)
- return word
-}
-
-export function replaceInputByFieldType<TData>({
- prev,
- currentWord,
- optionValue,
- value,
- field,
-}: {
- prev: string
- currentWord: string
- optionValue?: string | number | boolean | undefined // FIXME: use DataTableFilterField<TData>["options"][number];
- value: string
- field: DataTableFilterField<TData>
-}) {
- switch (field.type) {
- case 'checkbox': {
- if (currentWord.includes(ARRAY_DELIMITER)) {
- const words = currentWord.split(ARRAY_DELIMITER)
- words[words.length - 1] = `${optionValue}`
- const input = prev.replace(currentWord, words.join(ARRAY_DELIMITER))
- return `${input.trim()} `
- }
- }
- case 'slider': {
- if (currentWord.includes(SLIDER_DELIMITER)) {
- const words = currentWord.split(SLIDER_DELIMITER)
- words[words.length - 1] = `${optionValue}`
- const input = prev.replace(currentWord, words.join(SLIDER_DELIMITER))
- return `${input.trim()} `
- }
- }
- case 'timerange': {
- if (currentWord.includes(RANGE_DELIMITER)) {
- const words = currentWord.split(RANGE_DELIMITER)
- words[words.length - 1] = `${optionValue}`
- const input = prev.replace(currentWord, words.join(RANGE_DELIMITER))
- return `${input.trim()} `
- }
- }
- default: {
- const input = prev.replace(currentWord, value)
- return `${input.trim()} `
- }
- }
-}
-
-export function getFieldOptions<TData>({ field }: { field: DataTableFilterField<TData> }) {
- switch (field.type) {
- case 'slider': {
- return field.options?.length
- ? field.options
- .map(({ value }) => value)
- .sort((a, b) => Number(a) - Number(b))
- .filter(notEmpty)
- : Array.from({ length: field.max - field.min + 1 }, (_, i) => field.min + i) || []
- }
- default: {
- return field.options?.map(({ value }) => value).filter(notEmpty) || []
- }
- }
-}
-
-export function getFilterValue({
- value,
- search,
- currentWord,
-}: {
- value: string
- search: string
- keywords?: string[] | undefined
- currentWord: string
-}): number {
- /**
- * @example value "suggestion:public:true regions,ams,gru,fra"
- */
- if (value.startsWith('suggestion:')) {
- const rawValue = value.toLowerCase().replace('suggestion:', '')
- if (rawValue.includes(search)) return 1
- return 0
- }
-
- /** */
- if (value.toLowerCase().includes(currentWord.toLowerCase())) return 1
-
- /**
- * @example checkbox [filter, query] = ["regions", "ams,gru,fra"]
- * @example slider [filter, query] = ["p95", "0-3000"]
- * @example input [filter, query] = ["name", "api"]
- */
- const [filter, query] = currentWord.toLowerCase().split(':')
- if (query && value.startsWith(`${filter}:`)) {
- if (query.includes(ARRAY_DELIMITER)) {
- /**
- * array of n elements
- * @example queries = ["ams", "gru", "fra"]
- */
- const queries = query.split(ARRAY_DELIMITER)
- const rawValue = value.toLowerCase().replace(`${filter}:`, '')
- if (queries.some((item, i) => item === rawValue && i !== queries.length - 1)) return 0
- if (queries.some((item) => rawValue.includes(item))) return 1
- }
- if (query.includes(SLIDER_DELIMITER)) {
- /**
- * range between 2 elements
- * @example queries = ["0", "3000"]
- */
- const queries = query.split(SLIDER_DELIMITER)
- const rawValue = value.toLowerCase().replace(`${filter}:`, '')
-
- const rawValueAsNumber = Number.parseInt(rawValue)
- const queryAsNumber = Number.parseInt(queries[0])
-
- if (queryAsNumber < rawValueAsNumber) {
- if (rawValue.includes(queries[1])) return 1
- return 0
- }
- return 0
- }
- const rawValue = value.toLowerCase().replace(`${filter}:`, '')
- if (rawValue.includes(query)) return 1
- }
- return 0
-}
-
-export function getFieldValueByType<TData>({
- field,
- value,
-}: {
- field?: DataTableFilterField<TData>
- value: unknown
-}) {
- if (!field) return null
-
- switch (field.type) {
- case 'slider': {
- if (Array.isArray(value)) {
- return value.join(SLIDER_DELIMITER)
- }
- return value
- }
- case 'checkbox': {
- if (Array.isArray(value)) {
- return value.join(ARRAY_DELIMITER)
- }
- // REMINER: inversed logic
- if (typeof value === 'string') {
- return value.split(ARRAY_DELIMITER)
- }
- return value
- }
- case 'timerange': {
- if (Array.isArray(value)) {
- if (isArrayOfDates(value)) {
- return value.map((date) => date.getTime()).join(RANGE_DELIMITER)
- }
- return value.join(RANGE_DELIMITER)
- }
- if (value instanceof Date) {
- return value.getTime()
- }
- return value
- }
- default: {
- return value
- }
- }
-}
-
-export function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
- return value !== null && value !== undefined
-}
-
-export function columnFiltersParser<TData>({
- searchParamsParser,
- filterFields,
-}: {
- searchParamsParser: Record<string, ParserBuilder<any>>
- filterFields: DataTableFilterField<TData>[]
-}) {
- return {
- parse: (inputValue: string) => {
- // Use regex to properly extract field:value pairs
- // This properly handles spaces within values
- const filterPairs: Record<string, string> = {}
-
- // This regex properly extracts field:value pairs where:
- // 1. Values can contain spaces (both normal spaces and URL-encoded + characters)
- // 2. It finds word characters followed by a colon as the field name
- // 3. It then captures everything (including spaces and + characters) until
- // it finds another field:value pattern or the end of string
- // This solves the issue with values like "edge function" or "edge+function" in URLs
- const regex = /(\w+):([^]*?)(?=\s+\w+:|$)/g
- let match
-
- while ((match = regex.exec(inputValue)) !== null) {
- const [_, fieldName, fieldValue] = match
- if (fieldName && fieldValue) {
- filterPairs[fieldName] = fieldValue.trim()
- }
- }
-
- const searchParams = Object.entries(filterPairs).reduce(
- (prev, [key, value]) => {
- const parser = searchParamsParser[key]
- if (!parser) return prev
-
- prev[key] = parser.parse(value)
- return prev
- },
- {} as Record<string, unknown>
- )
-
- return searchParams
- },
- serialize: (columnFilters: ColumnFiltersState) => {
- const values = columnFilters.reduce((prev, curr) => {
- const { commandDisabled } = filterFields?.find((field) => curr.id === field.value) || {
- commandDisabled: true,
- } // if column filter is not found, disable the command by default
- const parser = searchParamsParser[curr.id]
-
- if (commandDisabled || !parser) return prev
-
- return `${prev}${curr.id}:${parser.serialize(curr.value)} `
- }, '')
-
- return values
- },
- }
-}
diff --git a/apps/studio/components/ui/DataTable/TimelineChart.tsx b/apps/studio/components/ui/DataTable/TimelineChart.tsx
index ed9263e1f10..236941804e8 100644
--- a/apps/studio/components/ui/DataTable/TimelineChart.tsx
+++ b/apps/studio/components/ui/DataTable/TimelineChart.tsx
@@ -97,7 +97,7 @@ export function TimelineChart<TChart extends BaseChartSchema>({
onMouseLeave={handleMouseUp}
style={{ cursor: 'crosshair' }}
>
- <CartesianGrid vertical={false} />
+ <CartesianGrid vertical={false} horizontal={false} />
<XAxis
dataKey={columnId}
tickLine={false}
diff --git a/apps/studio/pages/_app.tsx b/apps/studio/pages/_app.tsx
index 4ca8f2fd8d7..4013b561d64 100644
--- a/apps/studio/pages/_app.tsx
+++ b/apps/studio/pages/_app.tsx
@@ -169,8 +169,8 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
}, [])
return (
- <ErrorBoundary FallbackComponent={GlobalErrorBoundaryState} onError={errorBoundaryHandler}>
- <QueryClientProvider client={queryClient}>
+ <QueryClientProvider client={queryClient}>
+ <ErrorBoundary FallbackComponent={GlobalErrorBoundaryState} onError={errorBoundaryHandler}>
<NuqsAdapter>
<HydrationBoundary state={pageProps.dehydratedState}>
<AuthProvider>
@@ -245,9 +245,9 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
</AuthProvider>
</HydrationBoundary>
</NuqsAdapter>
- </QueryClientProvider>
- <TelemetryTagManager />
- </ErrorBoundary>
+ <TelemetryTagManager />
+ </ErrorBoundary>
+ </QueryClientProvider>
)
}
diff --git a/packages/ui-patterns/src/FilterBar/FilterBar.tsx b/packages/ui-patterns/src/FilterBar/FilterBar.tsx
index a77dbe4d04b..066572f1cdc 100644
--- a/packages/ui-patterns/src/FilterBar/FilterBar.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterBar.tsx
@@ -25,6 +25,14 @@ export type FilterBarProps = {
variant?: FilterBarVariant
icon?: React.ReactNode
onFilterChange: (filters: FilterGroupType) => void
+ /**
+ * Fires only on commit boundaries: menu item selected, operator/property/logical-operator
+ * change, condition removed, AI filter applied, Enter pressed in value input, or focus leaves
+ * the FilterBar. Use this when downstream state (URL params, table filters, queries) should
+ * only update once the user has finalized a value — `onFilterChange` fires on every keystroke
+ * and is intended for keeping the controlled `filters` prop in sync.
+ */
+ onApply?: (filters: FilterGroupType) => void
onFreeformTextChange: (freeformText: string) => void
}
@@ -49,11 +57,10 @@ function FilterBarContent({ className }: { className?: string }) {
>
<div
className={cn(
- 'relative flex items-center justify-center shrink-0 px-2 bg-surface-200',
- variant === 'pill' ? 'bg-transparent border-r-0' : 'border-r',
- !isLoading && 'cursor-pointer'
+ 'relative flex items-center justify-center shrink-0 px-2 bg-surface-200 cursor-pointer',
+ variant === 'pill' ? 'bg-transparent border-r-0' : 'border-r'
)}
- onClick={() => !isLoading && handleGroupFreeformFocus([])}
+ onClick={() => handleGroupFreeformFocus([])}
>
<div
className={cn(
@@ -119,6 +126,7 @@ export const FilterBar = forwardRef<FilterBarHandle, FilterBarProps>(function Fi
filterProperties,
filters,
onFilterChange,
+ onApply,
freeformText,
onFreeformTextChange,
actions,
@@ -136,6 +144,7 @@ export const FilterBar = forwardRef<FilterBarHandle, FilterBarProps>(function Fi
filterProperties={filterProperties}
filters={filters}
onFilterChange={onFilterChange}
+ onApply={onApply}
freeformText={freeformText}
onFreeformTextChange={onFreeformTextChange}
actions={actions}
diff --git a/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx b/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx
index bd34cc53c42..1b539c9ed57 100644
--- a/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterBarContext.tsx
@@ -42,6 +42,7 @@ export type FilterBarContextValue = {
highlightedConditionPath: number[] | null
onFilterChange: (filters: FilterGroup) => void
+ commitFilters: (filters: FilterGroup) => void
onFreeformTextChange: (text: string) => void
setActiveInput: (input: ActiveInputState) => void
handleInputChange: (path: number[], value: string) => void
@@ -89,6 +90,7 @@ export type FilterBarRootProps = {
filterProperties: FilterProperty[]
filters: FilterGroup
onFilterChange: (filters: FilterGroup) => void
+ onApply?: (filters: FilterGroup) => void
freeformText: string
onFreeformTextChange: (text: string) => void
actions?: FilterBarAction[]
@@ -110,6 +112,7 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
filterProperties,
filters,
onFilterChange,
+ onApply,
freeformText,
onFreeformTextChange,
actions,
@@ -122,6 +125,26 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
) {
const rootRef = useRef<HTMLDivElement>(null)
+ // Keep latest onApply in a ref so commitFilters/handleInputBlur don't need to be re-created
+ // (and downstream callbacks don't churn) when only the consumer's onApply identity changes.
+ const onApplyRef = useRef(onApply)
+ useEffect(() => {
+ onApplyRef.current = onApply
+ }, [onApply])
+
+ const filtersRef = useRef(filters)
+ useEffect(() => {
+ filtersRef.current = filters
+ }, [filters])
+
+ const commitFilters = useCallback(
+ (next: FilterGroup) => {
+ onFilterChange(next)
+ onApplyRef.current?.(next)
+ },
+ [onFilterChange]
+ )
+
const {
isLoading,
error,
@@ -161,9 +184,9 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
const handleOperatorChange = useCallback(
(path: number[], value: string) => {
const updatedFilters = updateNestedOperator(filters, path, value)
- onFilterChange(updatedFilters)
+ commitFilters(updatedFilters)
},
- [filters, onFilterChange]
+ [filters, commitFilters]
)
const { handleItemSelect } = useCommandHandling({
@@ -171,10 +194,10 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
setActiveInput,
activeFilters: filters,
onFilterChange,
+ commitFilters,
filterProperties,
freeformText,
onFreeformTextChange,
- handleInputChange,
handleOperatorChange,
newPathRef,
setIsCommandMenuVisible,
@@ -184,7 +207,7 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
activeInput,
setActiveInput,
activeFilters: filters,
- onFilterChange,
+ commitFilters,
highlightedConditionPath,
setHighlightedConditionPath,
})
@@ -254,6 +277,9 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
setIsCommandMenuVisible(false)
setActiveInput(null)
setHighlightedConditionPath(null)
+ // Focus has actually left the FilterBar — fire onApply with the latest filters so any
+ // value typed but never confirmed via Enter still gets pushed downstream.
+ onApplyRef.current?.(filtersRef.current)
}, 0)
}, [setIsCommandMenuVisible, setActiveInput, hideTimeoutRef, setHighlightedConditionPath])
@@ -299,27 +325,27 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
operator,
value
)
- onFilterChange(updatedFilters)
+ commitFilters(updatedFilters)
setActiveInput({ type: focusTarget, path })
},
- [filters, filterProperties, onFilterChange, setActiveInput]
+ [filters, filterProperties, commitFilters, setActiveInput]
)
const handleLogicalOperatorChange = useCallback(
(path: number[]) => {
const updatedFilters = updateNestedLogicalOperator(filters, path)
- onFilterChange(updatedFilters)
+ commitFilters(updatedFilters)
},
- [filters, onFilterChange]
+ [filters, commitFilters]
)
const handleRemoveCondition = useCallback(
(path: number[]) => {
const updatedFilters = removeFromGroup(filters, path)
- onFilterChange(updatedFilters)
+ commitFilters(updatedFilters)
setActiveInput(null)
},
- [filters, onFilterChange, setActiveInput]
+ [filters, commitFilters, setActiveInput]
)
// Cleanup hideTimeoutRef on unmount to prevent memory leaks
@@ -343,6 +369,7 @@ export const FilterBarRoot = forwardRef<FilterBarHandle, FilterBarRootProps>(fun
highlightedConditionPath,
onFilterChange,
+ commitFilters,
onFreeformTextChange,
setActiveInput,
handleInputChange,
diff --git a/packages/ui-patterns/src/FilterBar/FilterCondition.tsx b/packages/ui-patterns/src/FilterBar/FilterCondition.tsx
index 63bf814e574..e5954edff8d 100644
--- a/packages/ui-patterns/src/FilterBar/FilterCondition.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterCondition.tsx
@@ -30,7 +30,6 @@ export function FilterCondition({
const {
filters: rootFilters,
filterProperties,
- isLoading,
propertyOptionsCache,
loadingOptions,
handleInputChange,
@@ -178,12 +177,12 @@ export function FilterCondition({
// If the value options are only a custom component, open it immediately
useEffect(() => {
- if (!isActive || isLoading) return
+ if (!isActive) return
const hasOnlyCustom = valueItems.length > 0 && valueItems.every((i) => i.isCustom)
if (hasOnlyCustom && !showValueCustom) {
setShowValueCustom(true)
}
- }, [isActive, isLoading, valueItems, showValueCustom])
+ }, [isActive, valueItems, showValueCustom])
const handleOperatorBackspace = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
@@ -265,7 +264,7 @@ export function FilterCondition({
data-testid={`filter-condition-${property.name}`}
data-highlighted={isHighlighted}
>
- <Popover open={isPropertyActive && !isLoading && propertyItems.length > 0}>
+ <Popover open={isPropertyActive && propertyItems.length > 0}>
<PopoverAnchor asChild>
<div ref={propertyLabelRef} className="relative inline-flex items-center shrink-0">
{isPropertyActive ? (
@@ -319,7 +318,7 @@ export function FilterCondition({
/>
</PopoverContent>
</Popover>
- <Popover open={isOperatorActive && !isLoading && operatorItems.length > 0}>
+ <Popover open={isOperatorActive && operatorItems.length > 0}>
<PopoverAnchor asChild>
<div className="relative inline-block">
<Input
@@ -334,7 +333,6 @@ export function FilterCondition({
onBlur={handleOperatorBlur}
onKeyDown={handleOperatorKeyDown}
className="h-full border-none bg-transparent py-0 px-1 text-center text-xs md:text-xs focus:outline-hidden focus:ring-0 focus:shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 text-foreground w-full absolute left-0 top-0"
- disabled={isLoading}
aria-label={`Operator for ${property.label}`}
data-testid={`filter-operator-${property.name}`}
tabIndex={-1}
@@ -370,7 +368,7 @@ export function FilterCondition({
/>
</PopoverContent>
</Popover>
- <Popover open={isActive && !isLoading && (showValueCustom || valueItems.length > 0)}>
+ <Popover open={isActive && (showValueCustom || valueItems.length > 0)}>
<PopoverAnchor asChild>
<div className="relative inline-block max-w-[180px]">
<Input
@@ -382,7 +380,6 @@ export function FilterCondition({
onBlur={handleValueBlur}
onKeyDown={handleValueKeyDown}
className="h-full border-none bg-transparent py-0 px-1 text-xs md:text-xs focus:outline-hidden focus:ring-0 focus:shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 w-full absolute left-0 top-0"
- disabled={isLoading}
aria-label={`Value for ${property.label}`}
data-testid={`filter-value-${property.name}`}
tabIndex={-1}
diff --git a/packages/ui-patterns/src/FilterBar/FilterGroup.tsx b/packages/ui-patterns/src/FilterBar/FilterGroup.tsx
index 8582c02379c..3fcbab30195 100644
--- a/packages/ui-patterns/src/FilterBar/FilterGroup.tsx
+++ b/packages/ui-patterns/src/FilterBar/FilterGroup.tsx
@@ -21,7 +21,6 @@ export function FilterGroup({ group, path }: FilterGroupProps) {
filterProperties,
activeInput,
freeformText,
- isLoading,
supportsOperators,
actions,
variant,
@@ -176,7 +175,7 @@ export function FilterGroup({ group, path }: FilterGroupProps) {
</React.Fragment>
)
})}
- <Popover open={isActive && !isLoading && items.length > 0 && !highlightedConditionPath}>
+ <Popover open={isActive && items.length > 0 && !highlightedConditionPath}>
<PopoverAnchor asChild>
{isRootGroup ? (
<Input
@@ -191,7 +190,6 @@ export function FilterGroup({ group, path }: FilterGroupProps) {
placeholder={
group.conditions.length === 0 ? emptyPlaceholder : 'Add more filters...'
}
- disabled={isLoading}
data-testid="filter-bar-freeform-input"
autoComplete="off"
data-1p-ignore
@@ -210,7 +208,6 @@ export function FilterGroup({ group, path }: FilterGroupProps) {
onKeyDown={handleFreeformKeyDown}
className="h-full border-none bg-transparent py-0 text-xs md:text-xs focus:outline-hidden focus:ring-0 focus:shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 w-full absolute left-0 top-0 px-2"
placeholder="+ Add filter"
- disabled={isLoading}
autoComplete="off"
data-1p-ignore
data-lpignore="true"
diff --git a/packages/ui-patterns/src/FilterBar/types.ts b/packages/ui-patterns/src/FilterBar/types.ts
index 5f94dbce3be..eac3b5ddaf2 100644
--- a/packages/ui-patterns/src/FilterBar/types.ts
+++ b/packages/ui-patterns/src/FilterBar/types.ts
@@ -139,7 +139,7 @@ export type KeyboardNavigationConfig = {
activeInput: ActiveInputState
setActiveInput: (input: ActiveInputState) => void
activeFilters: FilterGroup
- onFilterChange: (filters: FilterGroup) => void
+ commitFilters: (filters: FilterGroup) => void
highlightedConditionPath: ConditionPath | null
setHighlightedConditionPath: (path: ConditionPath | null) => void
}
diff --git a/packages/ui-patterns/src/FilterBar/useCommandHandling.ts b/packages/ui-patterns/src/FilterBar/useCommandHandling.ts
index 5b3d4ccaa18..4e31aa47aae 100644
--- a/packages/ui-patterns/src/FilterBar/useCommandHandling.ts
+++ b/packages/ui-patterns/src/FilterBar/useCommandHandling.ts
@@ -5,6 +5,7 @@ import {
addFilterToGroup,
addGroupToGroup,
findGroupByPath,
+ isFilterOperatorObject,
updateNestedOperator,
updateNestedValue,
} from './utils'
@@ -14,10 +15,10 @@ export function useCommandHandling({
setActiveInput,
activeFilters,
onFilterChange,
+ commitFilters,
filterProperties,
freeformText,
onFreeformTextChange,
- handleInputChange,
handleOperatorChange,
newPathRef,
setIsCommandMenuVisible,
@@ -26,10 +27,10 @@ export function useCommandHandling({
setActiveInput: (input: ActiveInputState) => void
activeFilters: FilterGroup
onFilterChange: (filters: FilterGroup) => void
+ commitFilters: (filters: FilterGroup) => void
filterProperties: FilterProperty[]
freeformText: string
onFreeformTextChange: (text: string) => void
- handleInputChange: (path: number[], value: string) => void
handleOperatorChange: (path: number[], value: string) => void
newPathRef: React.MutableRefObject<number[]>
setIsCommandMenuVisible: (visible: boolean) => void
@@ -40,6 +41,8 @@ export function useCommandHandling({
const group = findGroupByPath(activeFilters, currentPath)
if (!group) return
+ // 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)
onFilterChange(updatedFilters)
newPathRef.current = [...currentPath, group.conditions.length]
@@ -55,12 +58,13 @@ export function useCommandHandling({
if (!activeInput || activeInput.type !== 'value') return
const path = activeInput.path
- handleInputChange(path, item.value)
+ const updated = updateNestedValue(activeFilters, path, item.value)
+ commitFilters(updated)
setTimeout(() => {
setActiveInput({ type: 'group', path: path.slice(0, -1) })
}, 0)
},
- [activeInput, handleInputChange, setActiveInput]
+ [activeInput, activeFilters, commitFilters, setActiveInput]
)
const handleOperatorCommand = useCallback(
@@ -76,12 +80,28 @@ export function useCommandHandling({
const handlePropertySelection = useCallback(
(selectedProperty: FilterProperty, currentPath: number[], group: FilterGroup) => {
- const updatedFilters = addFilterToGroup(activeFilters, currentPath, selectedProperty)
- onFilterChange(updatedFilters)
+ // Adding a new condition stub (property only, no operator/value yet) is structural —
+ // draft-only. onApply fires once the user picks an operator or value.
+ let updatedFilters = addFilterToGroup(activeFilters, currentPath, selectedProperty)
const newPath = [...currentPath, group.conditions.length]
+ // If the property only allows a single operator, pre-fill it and skip the operator step —
+ // the user otherwise has to hit Enter on a one-item dropdown before they can type a value.
+ const operators = selectedProperty.operators ?? []
+ const onlyOperator =
+ operators.length === 1
+ ? isFilterOperatorObject(operators[0])
+ ? operators[0].value
+ : operators[0]
+ : null
+
+ if (onlyOperator) {
+ updatedFilters = updateNestedOperator(updatedFilters, newPath, onlyOperator)
+ }
+ onFilterChange(updatedFilters)
+
setTimeout(() => {
- setActiveInput({ type: 'operator', path: newPath })
+ setActiveInput({ type: onlyOperator ? 'value' : 'operator', path: newPath })
}, 0)
},
[activeFilters, onFilterChange, setActiveInput]
@@ -137,7 +157,7 @@ export function useCommandHandling({
if (item.isDefaultOperator) {
const path = activeInput.path
const filtersWithOperator = updateNestedOperator(activeFilters, path, item.value)
- onFilterChange(updateNestedValue(filtersWithOperator, path, item.defaultValue ?? ''))
+ commitFilters(updateNestedValue(filtersWithOperator, path, item.defaultValue ?? ''))
// Added minor delay to ensure the filter is updated before navigating to the group
setTimeout(() => {
@@ -159,7 +179,7 @@ export function useCommandHandling({
handleValueCommand,
handleOperatorCommand,
handleGroupPropertyCommand,
- onFilterChange,
+ commitFilters,
setIsCommandMenuVisible,
]
)
diff --git a/packages/ui-patterns/src/FilterBar/useKeyboardNavigation.ts b/packages/ui-patterns/src/FilterBar/useKeyboardNavigation.ts
index cbc96bb5b66..2bc6c72c469 100644
--- a/packages/ui-patterns/src/FilterBar/useKeyboardNavigation.ts
+++ b/packages/ui-patterns/src/FilterBar/useKeyboardNavigation.ts
@@ -12,16 +12,16 @@ export function useKeyboardNavigation({
activeInput,
setActiveInput,
activeFilters,
- onFilterChange,
+ commitFilters,
highlightedConditionPath,
setHighlightedConditionPath,
}: KeyboardNavigationConfig) {
const removeByPath = useCallback(
(path: ConditionPath) => {
const updatedFilters = removeFromGroup(activeFilters, path)
- onFilterChange(updatedFilters)
+ commitFilters(updatedFilters)
},
- [activeFilters, onFilterChange]
+ [activeFilters, commitFilters]
)
const findFirstConditionInGroup = useCallback(
@@ -278,6 +278,10 @@ export function useKeyboardNavigation({
setHighlightedConditionPath(null)
} else if (activeInput?.type === 'value') {
e.preventDefault()
+ // Enter from a value input (with no menu item highlighted) is the user committing
+ // the typed value. `handleInputChange` has already pushed it through onFilterChange
+ // on each keystroke, so we just need to surface the commit via onApply here.
+ commitFilters(activeFilters)
setActiveInput({ type: 'group', path: activeInput.path.slice(0, -1) })
} else if (activeInput?.type === 'operator') {
e.preventDefault()
@@ -288,6 +292,8 @@ export function useKeyboardNavigation({
},
[
activeInput,
+ activeFilters,
+ commitFilters,
handleBackspace,
handleArrowLeft,
handleArrowRight,