Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(web): Make KeyValueFilterBuilder use design system (#17992)

Ben Bachem5e4bea920ecc
diff --git a/web/src/components/design-system/DropdownMenu/DropdownMenu.stories.tsx b/web/src/components/design-system/DropdownMenu/DropdownMenu.stories.tsx
index 94e3054d6e..f075225100 100644
--- a/web/src/components/design-system/DropdownMenu/DropdownMenu.stories.tsx
+++ b/web/src/components/design-system/DropdownMenu/DropdownMenu.stories.tsx
@@ -388,7 +388,7 @@ export const TestCheckboxAndSubmenu = meta.story({
const checkbox = body.getByRole("menuitemcheckbox", {
name: "Include output",
});
- await expect(checkbox).toHaveFocus();
+ await waitFor(() => expect(checkbox).toHaveFocus());
await userEvent.keyboard("{Enter}");
await expect(onCheckboxChange).toHaveBeenCalledWith(true);
await userEvent.keyboard("{ArrowDown}");
diff --git a/web/src/components/design-system/Input/Input.tsx b/web/src/components/design-system/Input/Input.tsx
index 047d3a17d6..81472b2426 100644
--- a/web/src/components/design-system/Input/Input.tsx
+++ b/web/src/components/design-system/Input/Input.tsx
@@ -4,6 +4,9 @@ import { InputControl } from "../internal/InputControl/InputControl";
type InputProps = Pick<
InputHTMLAttributes<HTMLInputElement>,
| "aria-describedby"
+ | "aria-controls"
+ | "aria-expanded"
+ | "aria-activedescendant"
| "aria-invalid"
| "aria-label"
| "aria-labelledby"
@@ -19,9 +22,11 @@ type InputProps = Pick<
| "onBlur"
| "onChange"
| "onFocus"
+ | "onKeyDown"
| "placeholder"
| "readOnly"
| "required"
+ | "role"
| "tabIndex"
| "type"
| "value"
diff --git a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.stories.tsx b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.stories.tsx
index 369c1c70b0..f06133b137 100644
--- a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.stories.tsx
+++ b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.stories.tsx
@@ -1,5 +1,12 @@
import { useState } from "react";
-import { expect, fireEvent, fn, userEvent, within } from "storybook/test";
+import {
+ expect,
+ fireEvent,
+ fn,
+ userEvent,
+ waitFor,
+ within,
+} from "storybook/test";
import preview from "../../../../.storybook/preview";
import { MultiSelectInput } from "./MultiSelectInput";
@@ -148,6 +155,40 @@ export const TestSelectsMultipleOptions = meta.story({
},
});
+export const TestHidesSelectAllWhileSearching = meta.story({
+ name: "(Test) Hides Select All While Searching",
+ args: {
+ value: [],
+ options,
+ onValueChange: fn(),
+ placeholder: "Select datasets",
+ selectedLabel: "",
+ searchPlaceholder: "Search datasets...",
+ emptyMessage: "No datasets found.",
+ selectAllLabel: "Select All",
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(canvas.getByRole("combobox"));
+ await waitFor(() =>
+ expect(body.getByRole("button", { name: "Select All" })).toBeVisible(),
+ );
+
+ const search = body.getByPlaceholderText("Search datasets...");
+ await userEvent.type(search, "production");
+ await expect(
+ body.queryByRole("button", { name: "Select All" }),
+ ).not.toBeInTheDocument();
+
+ await userEvent.clear(search);
+ await waitFor(() =>
+ expect(body.getByRole("button", { name: "Select All" })).toBeVisible(),
+ );
+ },
+});
+
export const TestKeepsWheelInsidePopover = meta.story({
name: "(Test) Keeps Wheel Inside Popover",
args: {
diff --git a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx
index 7e05fd659f..7631ccc8b9 100644
--- a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx
+++ b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx
@@ -26,7 +26,9 @@ type MultiSelectInputProps<V> = {
selectedLabel: string;
searchPlaceholder: string;
emptyMessage: string;
+ selectAllLabel?: string;
error?: boolean;
+ disabled?: boolean;
} & Pick<
React.ComponentPropsWithoutRef<"button">,
"id" | "aria-describedby" | "aria-invalid" | "aria-label"
@@ -41,24 +43,37 @@ function MultiSelectInputInner<V extends string>(
selectedLabel,
searchPlaceholder,
emptyMessage,
+ selectAllLabel,
error,
+ disabled,
...triggerProps
}: MultiSelectInputProps<V>,
ref: React.ForwardedRef<HTMLButtonElement>,
) {
const container = useLayerContainer("popover");
const [open, setOpen] = React.useState(false);
+ const [search, setSearch] = React.useState("");
const listId = React.useId();
+ const allSelected =
+ options.length > 0 &&
+ options.every((option) => option.disabled || value.includes(option.value));
return (
- <PopoverPrimitive.Root open={open} onOpenChange={setOpen}>
- <InputControl contentLayout="spread" error={error}>
+ <PopoverPrimitive.Root
+ open={!disabled && open}
+ onOpenChange={(nextOpen) => {
+ setOpen(nextOpen);
+ if (!nextOpen) setSearch("");
+ }}
+ >
+ <InputControl contentLayout="spread" error={error} disabled={disabled}>
<PopoverPrimitive.Trigger
ref={ref}
type="button"
role="combobox"
aria-controls={listId}
aria-expanded={open}
+ disabled={disabled}
{...triggerProps}
>
<span
@@ -84,8 +99,54 @@ function MultiSelectInputInner<V extends string>(
<InputDropdown.Root>
<CommandPrimitive>
<InputDropdown.Search>
- <CommandPrimitive.Input placeholder={searchPlaceholder} />
+ <CommandPrimitive.Input
+ placeholder={searchPlaceholder}
+ value={search}
+ onValueChange={setSearch}
+ />
</InputDropdown.Search>
+ {selectAllLabel &&
+ !search.trim() &&
+ options.some((option) => !option.disabled) && (
+ <InputDropdown.Option
+ highlight="focus"
+ checked={allSelected}
+ >
+ <button
+ type="button"
+ aria-pressed={allSelected}
+ onClick={() =>
+ onValueChange(
+ allSelected
+ ? value.filter((selectedValue) =>
+ options.every(
+ (option) =>
+ option.value !== selectedValue ||
+ option.disabled,
+ ),
+ )
+ : [
+ ...value,
+ ...options
+ .filter(
+ (option) =>
+ !option.disabled &&
+ !value.includes(option.value),
+ )
+ .map((option) => option.value),
+ ],
+ )
+ }
+ >
+ <InputDropdown.OptionContent
+ label={selectAllLabel}
+ title={selectAllLabel}
+ type="checkbox"
+ checked={allSelected}
+ />
+ </button>
+ </InputDropdown.Option>
+ )}
<InputDropdown.Empty>
<CommandPrimitive.Empty>
{emptyMessage}
diff --git a/web/src/components/design-system/SelectInput/SelectInput.stories.tsx b/web/src/components/design-system/SelectInput/SelectInput.stories.tsx
index c646df67a6..4ee6bf6dfa 100644
--- a/web/src/components/design-system/SelectInput/SelectInput.stories.tsx
+++ b/web/src/components/design-system/SelectInput/SelectInput.stories.tsx
@@ -91,6 +91,47 @@ export const WithLongText = meta.story({
),
});
+export const SearchableWithBadges = meta.story({
+ name: "(Test) Searchable with badges",
+ args: {
+ value: "quality",
+ placeholder: "Select a key",
+ search: { placeholder: "Search keys..." },
+ options: [
+ {
+ value: "quality",
+ label: "quality",
+ badges: [
+ { text: "Trace", color: "violet" },
+ { text: "Observation", color: "blue" },
+ ],
+ },
+ { value: "relevance", label: "relevance" },
+ ],
+ onValueChange: fn(),
+ },
+ render: (args) => {
+ const [value, setValue] = useState(args.value);
+ return (
+ <div className="w-64">
+ <SelectInput {...args} value={value} onValueChange={setValue} />
+ </div>
+ );
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ await userEvent.click(canvas.getByRole("combobox"));
+ await userEvent.type(
+ body.getByPlaceholderText("Search keys..."),
+ "relevance",
+ );
+ await expect(body.getByRole("option", { name: /relevance/ })).toBeVisible();
+ await userEvent.click(body.getByRole("option", { name: /relevance/ }));
+ await expect(canvas.getByRole("combobox")).toHaveTextContent("relevance");
+ },
+});
+
export const Empty = meta.story({
name: "(Test) Empty",
args: {
diff --git a/web/src/components/design-system/SelectInput/SelectInput.tsx b/web/src/components/design-system/SelectInput/SelectInput.tsx
index d0e36b6c26..9293f356bb 100644
--- a/web/src/components/design-system/SelectInput/SelectInput.tsx
+++ b/web/src/components/design-system/SelectInput/SelectInput.tsx
@@ -2,10 +2,13 @@
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
+import * as PopoverPrimitive from "@radix-ui/react-popover";
+import { Command as CommandPrimitive } from "cmdk";
-import { useCallback } from "react";
import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";
import { ChevronDown, ChevronUp } from "lucide-react";
+import { Badge } from "../Badge/Badge";
+import { stopScrollPropagation } from "@/src/hooks/stopScrollPropagation";
import { InputControl } from "../internal/InputControl/InputControl";
import { InputDropdown } from "../internal/InputDropdown/InputDropdown";
@@ -13,12 +16,18 @@ type SelectOption<V> =
| {
value: V;
label: string;
+ badges?: Array<
+ Pick<React.ComponentProps<typeof Badge>, "text" | "color" | "title">
+ >;
disabled?: false;
disabledReason?: never;
}
| {
value: V;
label: string;
+ badges?: Array<
+ Pick<React.ComponentProps<typeof Badge>, "text" | "color" | "title">
+ >;
disabled: true;
disabledReason: string;
};
@@ -38,6 +47,7 @@ type SelectInputProps<V> = {
onValueChange: (newValue: V) => void;
placeholder: string;
emptyMessage?: string;
+ search?: { placeholder: string };
error?: boolean;
} & Pick<
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>,
@@ -55,6 +65,7 @@ function SelectInputInner<V extends string>(
onValueChange,
placeholder,
emptyMessage = "No options available.",
+ search,
error,
...triggerProps
}: SelectInputProps<V>,
@@ -68,52 +79,161 @@ function SelectInputInner<V extends string>(
const hasOptions = options.some((node) =>
isSelectGroup(node) ? node.options.length > 0 : true,
);
- const renderNode = useCallback(
- (
- node: SelectInputNode<V>,
- hasPreviousGroup: boolean,
- ): React.ReactElement => {
- if (isSelectGroup(node)) {
- return (
- <React.Fragment key={node.id}>
- {hasPreviousGroup && (
- <SelectPrimitive.Separator className="bg-border my-2 h-px" />
- )}
- <SelectPrimitive.Group>
- <SelectPrimitive.Label className="text-muted-foreground px-1 py-1.5 text-xs font-bold">
- {node.label}
- </SelectPrimitive.Label>
- {node.options.map((option) => renderNode(option, false))}
- </SelectPrimitive.Group>
- </React.Fragment>
- );
- }
+ const listId = React.useId();
- return (
- <React.Fragment key={node.value}>
- {hasPreviousGroup && <div aria-hidden="true" className="h-4" />}
- <InputDropdown.Option highlight="focus">
- <SelectPrimitive.SelectItem
- value={node.value}
- disabled={node.disabled}
+ if (search) {
+ return (
+ <PopoverPrimitive.Root open={open} onOpenChange={setOpen}>
+ <InputControl
+ contentLayout="spread"
+ error={error}
+ disabled={triggerProps.disabled}
+ >
+ <PopoverPrimitive.Trigger
+ ref={ref}
+ type="button"
+ role="combobox"
+ aria-controls={listId}
+ aria-expanded={open}
+ title={selectedOption?.label}
+ {...triggerProps}
+ >
+ <span
+ className="min-w-0 flex-1 truncate text-left"
+ title={selectedOption?.label}
+ >
+ {selectedOption?.label ?? placeholder}
+ </span>
+ <ChevronDown className="size-4 shrink-0 opacity-50" />
+ </PopoverPrimitive.Trigger>
+ </InputControl>
+ <PopoverPrimitive.Portal container={container}>
+ <InputDropdown.Content width="popover-trigger">
+ <PopoverPrimitive.Content
+ align="start"
+ sideOffset={4}
+ onWheel={stopScrollPropagation()}
+ onTouchMove={stopScrollPropagation()}
>
- <InputDropdown.OptionContent
- type="checkmark"
- checked={value === node.value}
- label={
- <SelectPrimitive.ItemText>
- {node.label}
- </SelectPrimitive.ItemText>
- }
- title={node.disabled ? node.disabledReason : node.label}
- />
- </SelectPrimitive.SelectItem>
- </InputDropdown.Option>
+ <InputDropdown.Root>
+ <CommandPrimitive>
+ <InputDropdown.Search>
+ <CommandPrimitive.Input placeholder={search.placeholder} />
+ </InputDropdown.Search>
+ <InputDropdown.Empty>
+ <CommandPrimitive.Empty>
+ {emptyMessage}
+ </CommandPrimitive.Empty>
+ </InputDropdown.Empty>
+ <InputDropdown.List>
+ <CommandPrimitive.List id={listId}>
+ {options.map((node) => {
+ const group = isSelectGroup(node);
+ const items = group ? node.options : [node];
+ const content = items.map((option) => (
+ <InputDropdown.Option
+ key={option.value}
+ highlight="aria-selected"
+ checked={value === option.value}
+ >
+ <CommandPrimitive.Item
+ value={option.value}
+ keywords={[option.label]}
+ disabled={option.disabled}
+ onSelect={() => {
+ onValueChange(option.value);
+ setOpen(false);
+ }}
+ >
+ <InputDropdown.OptionContent
+ type="radio"
+ checked={value === option.value}
+ label={option.label}
+ title={
+ option.disabled
+ ? option.disabledReason
+ : option.label
+ }
+ />
+ {option.badges?.map((badge, index) => (
+ <Badge key={index} {...badge} />
+ ))}
+ </CommandPrimitive.Item>
+ </InputDropdown.Option>
+ ));
+
+ if (!group) {
+ return (
+ <React.Fragment key={node.value}>
+ {content}
+ </React.Fragment>
+ );
+ }
+ return (
+ <CommandPrimitive.Group
+ key={node.id}
+ heading={node.label}
+ >
+ {content}
+ </CommandPrimitive.Group>
+ );
+ })}
+ </CommandPrimitive.List>
+ </InputDropdown.List>
+ </CommandPrimitive>
+ </InputDropdown.Root>
+ </PopoverPrimitive.Content>
+ </InputDropdown.Content>
+ </PopoverPrimitive.Portal>
+ </PopoverPrimitive.Root>
+ );
+ }
+ const renderNode = (
+ node: SelectInputNode<V>,
+ hasPreviousGroup: boolean,
+ ): React.ReactElement => {
+ if (isSelectGroup(node)) {
+ return (
+ <React.Fragment key={node.id}>
+ {hasPreviousGroup && (
+ <SelectPrimitive.Separator className="bg-border my-2 h-px" />
+ )}
+ <SelectPrimitive.Group>
+ <SelectPrimitive.Label className="text-muted-foreground px-1 py-1.5 text-xs font-bold">
+ {node.label}
+ </SelectPrimitive.Label>
+ {node.options.map((option) => renderNode(option, false))}
+ </SelectPrimitive.Group>
</React.Fragment>
);
- },
- [value],
- );
+ }
+
+ return (
+ <React.Fragment key={node.value}>
+ {hasPreviousGroup && <div aria-hidden="true" className="h-4" />}
+ <InputDropdown.Option highlight="focus">
+ <SelectPrimitive.SelectItem
+ value={node.value}
+ disabled={node.disabled}
+ >
+ <InputDropdown.OptionContent
+ type="radio"
+ checked={value === node.value}
+ label={
+ <SelectPrimitive.ItemText>
+ {node.label}
+ </SelectPrimitive.ItemText>
+ }
+ title={node.disabled ? node.disabledReason : node.label}
+ />
+ {node.badges?.map((badge, index) => (
+ <Badge key={index} {...badge} />
+ ))}
+ </SelectPrimitive.SelectItem>
+ </InputDropdown.Option>
+ </React.Fragment>
+ );
+ };
return (
<SelectPrimitive.Root
diff --git a/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx b/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx
index 310860bf4f..43e82e26cf 100644
--- a/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx
+++ b/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx
@@ -112,9 +112,33 @@ function OptionContent({
label: ReactNode;
secondaryLabel?: string;
title: string;
- type: "checkbox" | "checkmark";
+ type: "checkbox" | "checkmark" | "radio";
checked: boolean;
}) {
+ let indicator = (
+ <Check
+ aria-hidden="true"
+ className={cn("size-4", checked ? "opacity-100" : "opacity-0")}
+ />
+ );
+ if (type === "checkbox") {
+ indicator = (
+ <Checkbox checked={checked} size="sm" tabIndex={-1} aria-hidden="true" />
+ );
+ } else if (type === "radio") {
+ indicator = (
+ <span
+ aria-hidden="true"
+ className={cn(
+ "border-control-border flex size-3.5 items-center justify-center rounded-full border shadow-sm",
+ checked && "border-control-fill",
+ )}
+ >
+ {checked && <span className="bg-control-fill size-1.5 rounded-full" />}
+ </span>
+ );
+ }
+
return (
<>
<span className="min-w-0 flex-1 truncate" title={title}>
@@ -126,22 +150,10 @@ function OptionContent({
<span
className={cn(
"pointer-events-none flex size-3.5 shrink-0 items-center justify-center",
- type === "checkbox" && "order-first",
+ (type === "checkbox" || type === "radio") && "order-first",
)}
>
- {type === "checkbox" ? (
- <Checkbox
- checked={checked}
- size="sm"
- tabIndex={-1}
- aria-hidden="true"
- />
- ) : (
- <Check
- aria-hidden="true"
- className={cn("size-4", checked ? "opacity-100" : "opacity-0")}
- />
- )}
+ {indicator}
</span>
</>
);
diff --git a/web/src/components/table/KeyValueFilterBuilder.stories.tsx b/web/src/components/table/KeyValueFilterBuilder.stories.tsx
new file mode 100644
index 0000000000..003cc10a11
--- /dev/null
+++ b/web/src/components/table/KeyValueFilterBuilder.stories.tsx
@@ -0,0 +1,208 @@
+import { useState } from "react";
+import { expect, fn, userEvent, within } from "storybook/test";
+import preview from "../../../.storybook/preview";
+import type {
+ BooleanKeyValueFilterEntry,
+ KeyValueFilterEntry,
+ NumericKeyValueFilterEntry,
+ StringKeyValueFilterEntry,
+} from "@/src/features/filters/hooks/useSidebarFilterState";
+import { KeyValueFilterBuilder } from "./KeyValueFilterBuilder";
+
+const meta = preview.meta({ component: KeyValueFilterBuilder });
+
+export const Categorical = meta.story({
+ args: {
+ mode: "categorical",
+ keyOptions: ["quality", "relevance", "helpfulness"],
+ keyLevels: { quality: ["trace"], relevance: ["observation"] },
+ availableValues: {
+ quality: ["good", "average", "poor"],
+ relevance: ["high", "medium", "low"],
+ helpfulness: ["yes", "no"],
+ },
+ activeFilters: [{ key: "quality", operator: "any of", value: ["good"] }],
+ onChange: fn(),
+ },
+ render: (args) => {
+ const [filters, setFilters] = useState<KeyValueFilterEntry[]>(
+ args.activeFilters as KeyValueFilterEntry[],
+ );
+ return (
+ <div className="w-80">
+ <KeyValueFilterBuilder
+ mode="categorical"
+ keyOptions={args.keyOptions}
+ keyLevels={args.keyLevels}
+ availableValues={
+ args.mode === "categorical" ? args.availableValues : {}
+ }
+ keyPlaceholder={args.keyPlaceholder}
+ activeFilters={filters}
+ onChange={setFilters}
+ />
+ </div>
+ );
+ },
+});
+
+export const Numeric = meta.story({
+ args: {
+ mode: "numeric",
+ keyOptions: ["accuracy", "latency", "cost"],
+ activeFilters: [{ key: "accuracy", operator: ">=", value: 0.8 }],
+ onChange: fn(),
+ },
+ render: (args) => {
+ const [filters, setFilters] = useState<NumericKeyValueFilterEntry[]>(
+ args.activeFilters as NumericKeyValueFilterEntry[],
+ );
+ return (
+ <div className="w-80">
+ <KeyValueFilterBuilder
+ mode="numeric"
+ keyOptions={args.keyOptions}
+ keyLevels={args.keyLevels}
+ keyPlaceholder={args.keyPlaceholder}
+ activeFilters={filters}
+ onChange={setFilters}
+ />
+ </div>
+ );
+ },
+});
+
+export const Boolean = meta.story({
+ args: {
+ mode: "boolean",
+ keyOptions: ["approved", "verified", "flagged"],
+ activeFilters: [{ key: "approved", operator: "=", value: true }],
+ onChange: fn(),
+ },
+ render: (args) => {
+ const [filters, setFilters] = useState<BooleanKeyValueFilterEntry[]>(
+ args.activeFilters as BooleanKeyValueFilterEntry[],
+ );
+ return (
+ <div className="w-80">
+ <KeyValueFilterBuilder
+ mode="boolean"
+ keyOptions={args.keyOptions}
+ keyLevels={args.keyLevels}
+ keyPlaceholder={args.keyPlaceholder}
+ activeFilters={filters}
+ onChange={setFilters}
+ />
+ </div>
+ );
+ },
+});
+
+export const String = meta.story({
+ args: {
+ mode: "string",
+ keyOptions: ["environment", "region", "user.id"],
+ keyDetails: {
+ environment: "string",
+ region: "string",
+ "user.id": "string",
+ },
+ valueOptions: {
+ environment: ["production", "staging", "development"],
+ region: ["us-east-1", "eu-west-1"],
+ },
+ activeFilters: [{ key: "environment", operator: "=", value: "production" }],
+ onChange: fn(),
+ },
+ render: (args) => {
+ const [filters, setFilters] = useState<StringKeyValueFilterEntry[]>(
+ args.activeFilters as StringKeyValueFilterEntry[],
+ );
+ return (
+ <div className="w-80">
+ <KeyValueFilterBuilder
+ mode="string"
+ keyOptions={args.keyOptions}
+ keyDetails={args.mode === "string" ? args.keyDetails : undefined}
+ valueOptions={args.mode === "string" ? args.valueOptions : undefined}
+ keyPlaceholder={args.keyPlaceholder}
+ activeFilters={filters}
+ onChange={setFilters}
+ />
+ </div>
+ );
+ },
+});
+
+export const FreeFormKey = meta.story({
+ args: {
+ mode: "numeric",
+ keyOptions: [],
+ activeFilters: [{ key: "custom.metric", operator: ">=", value: 0.8 }],
+ onChange: fn(),
+ },
+ render: (args) => {
+ const [filters, setFilters] = useState<NumericKeyValueFilterEntry[]>(
+ args.activeFilters as NumericKeyValueFilterEntry[],
+ );
+ return (
+ <div className="w-80">
+ <KeyValueFilterBuilder
+ mode="numeric"
+ keyOptions={args.keyOptions}
+ activeFilters={filters}
+ onChange={setFilters}
+ />
+ </div>
+ );
+ },
+});
+
+export const TestObservedKeySuggestionPreservesValue = meta.story({
+ name: "(Test) Observed Key Suggestion Preserves Value",
+ args: {
+ mode: "string",
+ keyOptions: ["environment", "region"],
+ keyDetails: { environment: "string", region: "string" },
+ valueOptions: { environment: ["production"], region: ["eu", "us"] },
+ activeFilters: [{ key: "re", operator: "=", value: "production" }],
+ onChange: fn(),
+ },
+ render: (args) => {
+ const [filters, setFilters] = useState<StringKeyValueFilterEntry[]>(
+ args.activeFilters as StringKeyValueFilterEntry[],
+ );
+ return (
+ <div className="w-80">
+ <KeyValueFilterBuilder
+ mode="string"
+ keyOptions={args.keyOptions}
+ keyDetails={args.mode === "string" ? args.keyDetails : undefined}
+ valueOptions={args.mode === "string" ? args.valueOptions : undefined}
+ activeFilters={filters}
+ onChange={(nextFilters) => {
+ setFilters(nextFilters);
+ if (args.mode === "string") {
+ args.onChange(nextFilters);
+ }
+ }}
+ />
+ </div>
+ );
+ },
+ play: async ({ args, canvasElement }) => {
+ const canvas = within(canvasElement);
+ const key = canvas.getByPlaceholderText("Key");
+
+ await userEvent.click(key);
+ await userEvent.keyboard("{ArrowDown}{Enter}");
+
+ await expect(key).toHaveValue("region");
+ await expect(canvas.getByPlaceholderText("Value")).toHaveValue(
+ "production",
+ );
+ await expect(args.onChange).toHaveBeenCalledWith([
+ { key: "region", operator: "=", value: "production" },
+ ]);
+ },
+});
diff --git a/web/src/components/table/key-value-filter-builder.tsx b/web/src/components/table/KeyValueFilterBuilder.tsx
similarity index 71%
rename from web/src/components/table/key-value-filter-builder.tsx
rename to web/src/components/table/KeyValueFilterBuilder.tsx
index 225aaafb39..25ae492cc8 100644
--- a/web/src/components/table/key-value-filter-builder.tsx
+++ b/web/src/components/table/KeyValueFilterBuilder.tsx
@@ -1,34 +1,18 @@
/* eslint-disable no-nested-ternary */
import { useId, useMemo, useState } from "react";
import { Button } from "@/src/components/ui/button";
-import { Input } from "@/src/components/ui/input";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";
+import { MultiSelectInput } from "@/src/components/design-system/MultiSelectInput/MultiSelectInput";
import {
Popover,
PopoverAnchor,
PopoverContent,
- PopoverTrigger,
} from "@/src/components/ui/popover";
-import {
- InputCommand,
- InputCommandEmpty,
- InputCommandGroup,
- InputCommandInput,
- InputCommandItem,
- InputCommandList,
-} from "@/src/components/ui/input-command";
-import { MultiSelect } from "@/src/features/filters/components/multi-select";
import { rankFacetOptions } from "@/src/features/filters/lib/facet-display";
import { isStringPresenceOperator } from "@/src/features/filters/lib/sidebar-filter-actions";
-import { Plus, X, Check, ChevronDown } from "lucide-react";
+import { Plus, X } from "lucide-react";
import { cn } from "@/src/utils/tailwind";
-import { ScoreTag } from "@/src/components/score-tag";
import type {
KeyScoreLevels,
KeyValueFilterEntry,
@@ -106,6 +90,25 @@ const BOOLEAN_OPERATOR_LABELS = {
"<>": "does not equal",
} as const;
+const CATEGORICAL_OPERATOR_OPTIONS = [
+ { value: "any of", label: "any of" },
+ { value: "none of", label: "none of" },
+];
+
+const NUMERIC_OPERATOR_OPTIONS = Object.entries(NUMERIC_OPERATOR_LABELS).map(
+ ([value, label]) => ({ value, label }),
+);
+const BOOLEAN_OPERATOR_OPTIONS = Object.entries(BOOLEAN_OPERATOR_LABELS).map(
+ ([value, label]) => ({ value, label }),
+);
+const STRING_OPERATOR_OPTIONS = Object.entries(STRING_OPERATOR_LABELS).map(
+ ([value, label]) => ({ value, label }),
+);
+const BOOLEAN_VALUE_OPTIONS = [
+ { value: "true", label: "true" },
+ { value: "false", label: "false" },
+];
+
// Enough to recognise what is available without turning the facet into a
// scroll surface.
const MAX_SUGGESTIONS = 10;
@@ -274,9 +277,6 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
const keyDetails = mode === "string" ? props.keyDetails : undefined;
const valueOptions = mode === "string" ? props.valueOptions : undefined;
- // Track which popover is open (by index)
- const [openPopoverIndex, setOpenPopoverIndex] = useState<number | null>(null);
-
// Applied rows belong to the parent; only incomplete edits stay local.
const [draftFilters, setDraftFilters] = useState<
{ index: number; filter: KeyedFilterEntry }[]
@@ -379,81 +379,27 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
{/* Key input and delete button row */}
<div className="flex items-center gap-2">
{hasKeyOptions ? (
- // Combobox for known keys
- <Popover
- open={openPopoverIndex === index}
- onOpenChange={(open) =>
- setOpenPopoverIndex(open ? index : null)
- }
- >
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- className="min-w-0 flex-1 justify-between overflow-hidden text-left font-normal"
- >
- {/* Selected name renders plain — level tags show only in
- the option rows below (design call: a selected filter
- needs no level tag, and long names must truncate). */}
- <span
- className={cn(
- "min-w-0 truncate",
- !filter.key && "text-muted-foreground",
- )}
- title={filter.key || keyPlaceholder}
- >
- {filter.key || keyPlaceholder}
- </span>
- <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-[200px] p-0" align="start">
- <InputCommand>
- <InputCommandInput
- placeholder="Search keys..."
- variant="bottom"
- />
- <InputCommandList>
- <InputCommandEmpty>No keys found.</InputCommandEmpty>
- <InputCommandGroup>
- {mergedKeyOptions.map((option) => (
- <InputCommandItem
- key={option}
- value={option}
- onSelect={(value) => {
- // Only update the key, preserve the existing value
- handleFilterChange(index, {
- key: value,
- });
- setOpenPopoverIndex(null); // Close after selection
- }}
- >
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- option === filter.key
- ? "visible"
- : "invisible",
- )}
- />
- <span
- className="min-w-0 flex-1 truncate"
- title={option}
- >
- {option}
- </span>
- {keyLevels?.[option]?.map((level) => (
- <span key={level} className="ml-1.5">
- <ScoreTag level={level} />
- </span>
- ))}
- </InputCommandItem>
- ))}
- </InputCommandGroup>
- </InputCommandList>
- </InputCommand>
- </PopoverContent>
- </Popover>
+ <div className="min-w-0 flex-1">
+ <SelectInput
+ value={filter.key}
+ placeholder={keyPlaceholder}
+ search={{ placeholder: "Search keys..." }}
+ emptyMessage="No keys found."
+ options={mergedKeyOptions.map((option) => ({
+ value: option,
+ label: option,
+ badges: keyLevels?.[option]?.map((level) => ({
+ text: level === "trace" ? "Trace" : "Observation",
+ title: `${level === "trace" ? "Trace" : "Observation"}-level score`,
+ color:
+ level === "trace"
+ ? ("violet" as const)
+ : ("blue" as const),
+ })),
+ }))}
+ onValueChange={(key) => handleFilterChange(index, { key })}
+ />
+ </div>
) : (
// Free-form key, with observed keys offered as suggestions.
// Only the key changes — the row's value is preserved.
@@ -482,28 +428,33 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
{mode === "categorical" ? (
<>
{/* Operator select */}
- <Select
+ <SelectInput
value={filter.operator}
+ options={CATEGORICAL_OPERATOR_OPTIONS}
+ placeholder="Operator"
onValueChange={(value) =>
handleFilterChange(index, {
operator: value as "any of" | "none of",
})
}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="any of">any of</SelectItem>
- <SelectItem value="none of">none of</SelectItem>
- </SelectContent>
- </Select>
+ />
{/* Values multi-select */}
- <MultiSelect
- title="Values"
- options={availableValuesForKey.map((v) => ({ value: v }))}
- values={filter.value as string[]}
+ <MultiSelectInput
+ placeholder="Select"
+ selectedLabel={`${(filter.value as string[]).length} selected`}
+ searchPlaceholder="Values"
+ emptyMessage="No results found."
+ selectAllLabel="Select All"
+ options={Array.from(
+ new Set([
+ ...availableValuesForKey,
+ ...(filter.value as string[]),
+ ]),
+ )
+ .filter((value) => value.length > 0)
+ .map((value) => ({ value, label: value }))}
+ value={filter.value as string[]}
onValueChange={(values) =>
handleFilterChange(index, { value: values })
}
@@ -513,27 +464,16 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
) : mode === "numeric" ? (
<>
{/* Numeric operator select */}
- <Select
+ <SelectInput
value={filter.operator}
+ options={NUMERIC_OPERATOR_OPTIONS}
+ placeholder="Operator"
onValueChange={(value) =>
handleFilterChange(index, {
operator: value as "=" | ">" | "<" | ">=" | "<=",
})
}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {Object.entries(NUMERIC_OPERATOR_LABELS).map(
- ([op, label]) => (
- <SelectItem key={op} value={op}>
- {label}
- </SelectItem>
- ),
- )}
- </SelectContent>
- </Select>
+ />
{/* Numeric value input */}
<Input
@@ -551,55 +491,40 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
</>
) : mode === "boolean" ? (
<>
- <Select
+ <SelectInput
value={filter.operator}
+ options={BOOLEAN_OPERATOR_OPTIONS}
+ placeholder="Operator"
onValueChange={(value) =>
handleFilterChange(index, {
operator: value as "=" | "<>",
})
}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {Object.entries(BOOLEAN_OPERATOR_LABELS).map(
- ([op, label]) => (
- <SelectItem key={op} value={op}>
- {label}
- </SelectItem>
- ),
- )}
- </SelectContent>
- </Select>
+ />
- <Select
+ <SelectInput
value={
typeof filter.value === "boolean"
? String(filter.value)
- : undefined
+ : ""
}
+ options={BOOLEAN_VALUE_OPTIONS}
+ placeholder="Value"
onValueChange={(value) =>
handleFilterChange(index, {
value: value === "true",
})
}
disabled={!filter.key}
- >
- <SelectTrigger>
- <SelectValue placeholder="Value" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="true">true</SelectItem>
- <SelectItem value="false">false</SelectItem>
- </SelectContent>
- </Select>
+ />
</>
) : (
<>
{/* String operator select */}
- <Select
+ <SelectInput
value={filter.operator}
+ options={STRING_OPERATOR_OPTIONS}
+ placeholder="Operator"
onValueChange={(value) => {
const operator = value as StringOperator;
handleFilterChange(index, {
@@ -611,20 +536,7 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
: {}),
});
}}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {Object.entries(STRING_OPERATOR_LABELS).map(
- ([op, label]) => (
- <SelectItem key={op} value={op}>
- {label}
- </SelectItem>
- ),
- )}
- </SelectContent>
- </Select>
+ />
{/* String value input, hidden for value-less presence operators */}
{isStringPresenceOperator(filter.operator) ? null : (
diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsx
index 421b625f81..f3873fb086 100644
--- a/web/src/components/table/data-table-controls.tsx
+++ b/web/src/components/table/data-table-controls.tsx
@@ -92,7 +92,7 @@ import type {
StringKeyValueFilterEntry,
TextFilterEntry,
} from "@/src/features/filters/hooks/useSidebarFilterState";
-import { KeyValueFilterBuilder } from "@/src/components/table/key-value-filter-builder";
+import { KeyValueFilterBuilder } from "@/src/components/table/KeyValueFilterBuilder";
import {
Popover,
PopoverContent,
diff --git a/web/src/components/table/key-value-filter-builder.clienttest.tsx b/web/src/components/table/key-value-filter-builder.clienttest.tsx
index bc56b833c2..bd120b7dd3 100644
--- a/web/src/components/table/key-value-filter-builder.clienttest.tsx
+++ b/web/src/components/table/key-value-filter-builder.clienttest.tsx
@@ -2,7 +2,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
import { useState } from "react";
import type { FilterState } from "@langfuse/shared";
import { applyKeyedFilterEntries } from "@/src/features/filters/lib/sidebar-filter-actions";
-import { KeyValueFilterBuilder } from "./key-value-filter-builder";
+import { KeyValueFilterBuilder } from "./KeyValueFilterBuilder";
const noop = () => {};
diff --git a/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx b/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx
index 603b50188d..f9efc5787b 100644
--- a/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx
+++ b/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx
@@ -19,7 +19,7 @@ import {
useSidebarFilterState,
} from "@/src/features/filters";
import { useTableViewManager } from "../../components/table/table-view-presets/hooks/useTableViewManager";
-import { KeyValueFilterBuilder } from "@/src/components/table/key-value-filter-builder";
+import { KeyValueFilterBuilder } from "@/src/components/table/KeyValueFilterBuilder";
import { useOrderByState } from "@/src/features/orderBy";
import {
demoteViewOnUserFilterEdit,
@@ -407,6 +407,17 @@ const applyPresetAndAssertActive = async () => {
};
describe("saved-view demotion on user filter edits", () => {
+ beforeAll(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ });
+
beforeEach(() => {
vi.clearAllMocks();
sessionStorage.clear();
diff --git a/web/src/features/filters/metadataSuggestionParity.clienttest.tsx b/web/src/features/filters/metadataSuggestionParity.clienttest.tsx
index 573e997646..9c53986cd8 100644
--- a/web/src/features/filters/metadataSuggestionParity.clienttest.tsx
+++ b/web/src/features/filters/metadataSuggestionParity.clienttest.tsx
@@ -9,7 +9,7 @@
*/
import { fireEvent, render, screen } from "@testing-library/react";
-import { KeyValueFilterBuilder } from "@/src/components/table/key-value-filter-builder";
+import { KeyValueFilterBuilder } from "@/src/components/table/KeyValueFilterBuilder";
import { observedMetadataOptions } from "@/src/fns/observedMetadata/metadataPaths";
import {
useSidebarFilterState,
@@ -71,6 +71,14 @@ function MetadataFacetHarness() {
describe("metadata suggestions in the filter sidebar", () => {
beforeAll(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
Element.prototype.scrollIntoView = vi.fn();
});