Skip to content

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

fix(web): Create `MultiSelectInput` & update `NewDatasetItemForm` (#17139)

Ben Bachem4c63fadbd3bb
diff --git a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.stories.tsx b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.stories.tsx
new file mode 100644
index 0000000000..26a57847f0
--- /dev/null
+++ b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.stories.tsx
@@ -0,0 +1,199 @@
+import { useState } from "react";
+import { expect, fireEvent, fn, userEvent, within } from "storybook/test";
+
+import preview from "../../../../.storybook/preview";
+import { MultiSelectInput } from "./MultiSelectInput";
+
+const longOptionLabel =
+ "This is a very long option label that should remain on a single line without wrapping";
+
+const options = [
+ { value: "evaluation", label: "Evaluation" },
+ { value: "production", label: "Production" },
+ { value: "regression", label: "Regression", secondaryLabel: "(current)" },
+];
+
+const largeOptions = Array.from({ length: 100 }, (_, index) => {
+ const number = String(index + 1).padStart(3, "0");
+
+ return {
+ value: `dataset-${number}`,
+ label: `Dataset ${number}`,
+ };
+});
+
+const meta = preview.meta({
+ component: MultiSelectInput,
+});
+
+export const Default = meta.story({
+ args: {
+ value: ["evaluation"],
+ options,
+ onValueChange: fn(),
+ placeholder: "Select datasets",
+ selectedLabel: "1 dataset selected",
+ searchPlaceholder: "Search datasets...",
+ emptyMessage: "No datasets found.",
+ },
+ render: (args) => {
+ const [value, setValue] = useState(args.value);
+
+ return (
+ <MultiSelectInput
+ {...args}
+ value={value}
+ selectedLabel={`${value.length} dataset${value.length === 1 ? "" : "s"} selected`}
+ onValueChange={(newValue) => {
+ setValue(newValue);
+ args.onValueChange(newValue);
+ }}
+ />
+ );
+ },
+});
+
+export const WithLongText = meta.story({
+ args: {
+ value: ["long-option"],
+ options: [{ value: "long-option", label: longOptionLabel }],
+ onValueChange: fn(),
+ placeholder: "Select an option",
+ selectedLabel: longOptionLabel,
+ searchPlaceholder: "Search options...",
+ emptyMessage: "No options found.",
+ },
+ render: (args) => (
+ <div className="w-64">
+ <MultiSelectInput {...args} />
+ </div>
+ ),
+});
+
+export const Empty = meta.story({
+ args: {
+ value: [],
+ options: [],
+ onValueChange: fn(),
+ placeholder: "Select datasets",
+ selectedLabel: "",
+ searchPlaceholder: "Search datasets...",
+ emptyMessage: "No datasets found.",
+ },
+});
+
+export const LargeList = meta.story({
+ args: {
+ value: ["dataset-001", "dataset-050", "dataset-100"],
+ options: largeOptions,
+ onValueChange: fn(),
+ placeholder: "Select datasets",
+ selectedLabel: "3 datasets selected",
+ searchPlaceholder: "Search datasets...",
+ emptyMessage: "No datasets found.",
+ },
+});
+
+export const TestSelectsMultipleOptions = meta.story({
+ name: "(Test) Selects Multiple Options",
+ args: {
+ value: ["evaluation"],
+ options,
+ onValueChange: fn(),
+ placeholder: "Select datasets",
+ selectedLabel: "1 dataset selected",
+ searchPlaceholder: "Search datasets...",
+ emptyMessage: "No datasets found.",
+ },
+ play: async ({ args, canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(canvas.getByRole("combobox"));
+ await userEvent.click(body.getByText("Production"));
+
+ await expect(args.onValueChange).toHaveBeenCalledWith([
+ "evaluation",
+ "production",
+ ]);
+ },
+});
+
+export const TestKeepsWheelInsidePopover = meta.story({
+ name: "(Test) Keeps Wheel Inside Popover",
+ args: {
+ value: [],
+ options: largeOptions,
+ onValueChange: fn(),
+ placeholder: "Select datasets",
+ selectedLabel: "",
+ searchPlaceholder: "Search datasets...",
+ emptyMessage: "No datasets found.",
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const bodyElement = canvasElement.ownerDocument.body;
+ const body = within(bodyElement);
+ const onWheel = fn();
+ const onTouchMove = fn();
+ bodyElement.addEventListener("wheel", onWheel);
+ bodyElement.addEventListener("touchmove", onTouchMove);
+
+ await userEvent.click(canvas.getByRole("combobox"));
+ fireEvent.wheel(body.getByRole("listbox"));
+ fireEvent.touchMove(body.getByRole("listbox"));
+
+ await expect(onWheel).not.toHaveBeenCalled();
+ await expect(onTouchMove).not.toHaveBeenCalled();
+ bodyElement.removeEventListener("wheel", onWheel);
+ bodyElement.removeEventListener("touchmove", onTouchMove);
+ },
+});
+
+export const TestKeepsOverlappingLabelsDistinct = meta.story({
+ name: "(Test) Keeps Overlapping Labels Distinct",
+ args: {
+ value: [],
+ options: [
+ { value: "dataset-uppercase", label: "Test" },
+ { value: "dataset-lowercase", label: "test" },
+ ],
+ onValueChange: fn(),
+ placeholder: "Select datasets",
+ selectedLabel: "",
+ searchPlaceholder: "Search datasets...",
+ emptyMessage: "No datasets found.",
+ },
+ play: async ({ args, canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(canvas.getByRole("combobox"));
+ await userEvent.type(
+ body.getByPlaceholderText("Search datasets..."),
+ "test",
+ );
+ const renderedOptions = body.getAllByRole("option");
+ const uppercaseOption = body.getByRole("option", {
+ name: /^Test$/,
+ });
+ const lowercaseOption = body.getByRole("option", {
+ name: /^test$/,
+ });
+
+ await expect(renderedOptions).toHaveLength(2);
+ await expect(uppercaseOption).toHaveAttribute(
+ "data-value",
+ "dataset-uppercase",
+ );
+ await expect(lowercaseOption).toHaveAttribute(
+ "data-value",
+ "dataset-lowercase",
+ );
+ await userEvent.click(lowercaseOption);
+
+ await expect(args.onValueChange).toHaveBeenCalledWith([
+ "dataset-lowercase",
+ ]);
+ },
+});
diff --git a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx
new file mode 100644
index 0000000000..9f6e177cd9
--- /dev/null
+++ b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx
@@ -0,0 +1,170 @@
+/* eslint-disable boundaries/dependencies */
+"use client";
+
+import * as React from "react";
+import * as PopoverPrimitive from "@radix-ui/react-popover";
+import { Command as CommandPrimitive } from "cmdk";
+import { Check, ChevronDown, Search } from "lucide-react";
+
+import { useScrollGradients } from "@/src/hooks/useScrollGradients";
+import { cn } from "@/src/utils/tailwind";
+import { stopScrollPropagation, useLayerContainer } from "../../ui/layer";
+
+type MultiSelectOption<V> = {
+ value: V;
+ label: string;
+ secondaryLabel?: string;
+};
+
+type MultiSelectInputProps<V> = {
+ value: V[];
+ options: MultiSelectOption<V>[];
+ onValueChange: (newValue: V[]) => void;
+ placeholder: string;
+ selectedLabel: string;
+ searchPlaceholder: string;
+ emptyMessage: string;
+} & Pick<
+ React.ComponentPropsWithoutRef<"button">,
+ "id" | "aria-describedby" | "aria-invalid"
+>;
+
+function MultiSelectInputInner<V extends string>(
+ {
+ value,
+ options,
+ onValueChange,
+ placeholder,
+ selectedLabel,
+ searchPlaceholder,
+ emptyMessage,
+ ...triggerProps
+ }: MultiSelectInputProps<V>,
+ ref: React.ForwardedRef<HTMLButtonElement>,
+) {
+ const container = useLayerContainer("popover");
+ const [open, setOpen] = React.useState(false);
+ const listId = React.useId();
+ const { register, recompute, top, bottom } =
+ useScrollGradients<HTMLDivElement>(true);
+
+ return (
+ <PopoverPrimitive.Root open={open} onOpenChange={setOpen}>
+ <PopoverPrimitive.Trigger asChild>
+ <button
+ ref={ref}
+ type="button"
+ role="combobox"
+ aria-controls={listId}
+ aria-expanded={open}
+ className={cn(
+ "border-input bg-background ring-offset-background placeholder:text-foreground-tertiary focus:ring-ring disabled:bg-muted/50 flex h-8 w-full items-center justify-between gap-1 rounded-md border px-3 py-2 text-sm focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
+ value.length === 0 && "text-muted-foreground",
+ )}
+ {...triggerProps}
+ >
+ <span
+ className="min-w-0 flex-1 truncate text-left"
+ title={value.length > 0 ? selectedLabel : undefined}
+ >
+ {value.length > 0 ? selectedLabel : placeholder}
+ </span>
+ <ChevronDown className="size-4 shrink-0 opacity-50" />
+ </button>
+ </PopoverPrimitive.Trigger>
+ <PopoverPrimitive.Portal container={container}>
+ <PopoverPrimitive.Content
+ align="start"
+ sideOffset={4}
+ onWheel={stopScrollPropagation()}
+ onTouchMove={stopScrollPropagation()}
+ className="bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative w-(--radix-popover-trigger-width) min-w-32 overflow-hidden rounded-md border shadow-md outline-hidden"
+ >
+ <CommandPrimitive className="bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md">
+ <div className="flex items-center border-b px-2">
+ <Search className="size-4 shrink-0 opacity-50" />
+ <CommandPrimitive.Input
+ placeholder={searchPlaceholder}
+ className="placeholder:text-foreground-tertiary flex h-8 w-full rounded border-transparent bg-transparent px-2 py-3 text-sm outline-hidden focus:border-0 focus:border-none focus:border-transparent focus:ring-0 disabled:cursor-not-allowed disabled:opacity-50"
+ />
+ </div>
+ <CommandPrimitive.Empty className="py-6 text-center text-sm">
+ {emptyMessage}
+ </CommandPrimitive.Empty>
+ <CommandPrimitive.List
+ id={listId}
+ ref={register}
+ onScroll={recompute}
+ className={cn(
+ "before:from-popover after:from-popover max-h-96 overflow-auto p-1.5 before:pointer-events-none before:sticky before:-top-1.5 before:z-2 before:-mx-1.5 before:-mb-6 before:block before:h-6 before:bg-linear-to-b before:to-transparent before:content-[''] after:pointer-events-none after:sticky after:-bottom-1.5 after:z-2 after:-mx-1.5 after:-mt-6 after:block after:h-6 after:bg-linear-to-t after:to-transparent after:content-['']",
+ top ? "before:opacity-100" : "before:opacity-0",
+ bottom ? "after:opacity-100" : "after:opacity-0",
+ )}
+ >
+ <CommandPrimitive.Group className="text-foreground overflow-hidden">
+ {options.map((option) => {
+ const isSelected = value.includes(option.value);
+
+ return (
+ <CommandPrimitive.Item
+ value={option.value}
+ keywords={[option.label]}
+ key={option.value}
+ className="aria-selected:bg-accent aria-selected:text-accent-foreground relative flex w-full cursor-default items-center rounded-sm px-1.5 py-1.5 text-sm outline-hidden select-none"
+ onSelect={() => {
+ if (isSelected) {
+ onValueChange(
+ value.filter(
+ (selectedValue) => selectedValue !== option.value,
+ ),
+ );
+ return;
+ }
+
+ onValueChange([...value, option.value]);
+ }}
+ >
+ <span
+ className="min-w-0 flex-1 truncate"
+ title={option.label}
+ >
+ {option.label}
+ {option.secondaryLabel && (
+ <span className="text-muted-foreground ml-1">
+ {option.secondaryLabel}
+ </span>
+ )}
+ </span>
+ <span className="ml-auto flex size-3.5 shrink-0 items-center justify-center">
+ <Check
+ className={cn(
+ "size-4",
+ isSelected ? "opacity-100" : "opacity-0",
+ )}
+ />
+ </span>
+ </CommandPrimitive.Item>
+ );
+ })}
+ </CommandPrimitive.Group>
+ </CommandPrimitive.List>
+ </CommandPrimitive>
+ </PopoverPrimitive.Content>
+ </PopoverPrimitive.Portal>
+ </PopoverPrimitive.Root>
+ );
+}
+
+type MultiSelectInputComponent = {
+ <V extends string>(
+ props: MultiSelectInputProps<V> & React.RefAttributes<HTMLButtonElement>,
+ ): React.ReactElement | null;
+
+ displayName?: string;
+};
+
+export const MultiSelectInput = React.forwardRef(
+ MultiSelectInputInner,
+) as MultiSelectInputComponent;
+
+MultiSelectInput.displayName = "MultiSelectInput";
diff --git a/web/src/components/design-system/SelectInput/SelectInput.tsx b/web/src/components/design-system/SelectInput/SelectInput.tsx
index f2c2ffd2f5..2d07d15cf0 100644
--- a/web/src/components/design-system/SelectInput/SelectInput.tsx
+++ b/web/src/components/design-system/SelectInput/SelectInput.tsx
@@ -175,7 +175,7 @@ function SelectInputInner<V extends string>(
ref={register}
onScroll={recompute}
className={cn(
- "before:from-popover after:from-popover max-h-96 overflow-auto p-1.5 before:pointer-events-none before:sticky before:top-0 before:z-2 before:-mx-1.5 before:-mb-6 before:block before:h-6 before:bg-linear-to-b before:to-transparent before:content-[''] after:pointer-events-none after:sticky after:bottom-0 after:z-2 after:-mx-1.5 after:-mt-6 after:block after:h-6 after:bg-linear-to-t after:to-transparent after:content-['']",
+ "before:from-popover after:from-popover max-h-96 overflow-auto p-1.5 before:pointer-events-none before:sticky before:-top-1.5 before:z-2 before:-mx-1.5 before:-mb-6 before:block before:h-6 before:bg-linear-to-b before:to-transparent before:content-[''] after:pointer-events-none after:sticky after:-bottom-1.5 after:z-2 after:-mx-1.5 after:-mt-6 after:block after:h-6 after:bg-linear-to-t after:to-transparent after:content-['']",
top ? "before:opacity-100" : "before:opacity-0",
bottom ? "after:opacity-100" : "after:opacity-0",
)}
diff --git a/web/src/features/datasets/components/NewDatasetItemForm.tsx b/web/src/features/datasets/components/NewDatasetItemForm.tsx
index e42723acb8..e6ff66c50f 100644
--- a/web/src/features/datasets/components/NewDatasetItemForm.tsx
+++ b/web/src/features/datasets/components/NewDatasetItemForm.tsx
@@ -42,22 +42,9 @@ import {
} from "./DatasetItemMediaAttachments";
import { DatasetItemFieldSchemaErrors } from "./DatasetItemFieldSchemaErrors";
import { generateSchemaExample } from "../lib/generateSchemaExample";
-import {
- InputCommand,
- InputCommandEmpty,
- InputCommandGroup,
- InputCommandInput,
- InputCommandItem,
-} from "@/src/components/ui/input-command";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/src/components/ui/popover";
-import { Check, ChevronsUpDown } from "lucide-react";
-import { Badge } from "@/src/components/ui/badge";
-import { ScrollArea } from "@/src/components/ui/scroll-area";
import { DialogBody, DialogFooter } from "@/src/components/ui/dialog";
+import { MultiSelectInput } from "@/src/components/design-system/MultiSelectInput/MultiSelectInput";
+import { Badge } from "@/src/components/ui/badge";
import {
isValidDatasetJson,
parseDatasetJson,
@@ -351,84 +338,38 @@ export const NewDatasetItemForm = (props: {
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Target datasets</FormLabel>
- <Popover>
- <PopoverTrigger asChild>
- <FormControl>
- <Button
- variant="outline"
- role="combobox"
- className={cn(
- "w-full justify-between",
- !field.value.length && "text-muted-foreground",
- )}
- >
- {field.value.length > 0
- ? `${field.value.length} dataset${field.value.length > 1 ? "s" : ""} selected`
- : "Select datasets"}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </FormControl>
- </PopoverTrigger>
- <PopoverContent className="p-0">
- <InputCommand>
- <InputCommandInput
- placeholder="Search datasets..."
- variant="bottom"
- />
- <InputCommandEmpty>
- No datasets found.
- </InputCommandEmpty>
- <InputCommandGroup>
- <ScrollArea className="h-fit">
- {datasets.data?.map((dataset) => (
- <InputCommandItem
- value={dataset.name}
- key={dataset.id}
- onSelect={() => {
- const newValue = field.value.includes(
- dataset.id,
- )
- ? field.value.filter(
- (id) => id !== dataset.id,
- )
- : [...field.value, dataset.id];
- field.onChange(newValue);
- }}
- >
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- field.value.includes(dataset.id)
- ? "opacity-100"
- : "opacity-0",
- )}
- />
- {dataset.name}
- {dataset.id === props.currentDatasetId && (
- <span className="text-muted-foreground ml-1">
- (current)
- </span>
- )}
- </InputCommandItem>
- ))}
- </ScrollArea>
- </InputCommandGroup>
- </InputCommand>
- </PopoverContent>
- </Popover>
+ <FormControl>
+ <MultiSelectInput
+ value={field.value}
+ options={(datasets.data ?? []).map((dataset) => ({
+ value: dataset.id,
+ label: dataset.name,
+ secondaryLabel:
+ dataset.id === props.currentDatasetId
+ ? "(current)"
+ : undefined,
+ }))}
+ onValueChange={field.onChange}
+ placeholder="Select datasets"
+ selectedLabel={`${field.value.length} dataset${field.value.length > 1 ? "s" : ""} selected`}
+ searchPlaceholder="Search datasets..."
+ emptyMessage="No datasets found."
+ />
+ </FormControl>
{field.value.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1">
{field.value.map((datasetId) => {
const dataset = datasets.data?.find(
- (d) => d.id === datasetId,
+ (item) => item.id === datasetId,
);
+
return (
<Badge
key={datasetId}
variant="secondary"
className="mr-1 mb-1"
>
- {dataset?.name || datasetId}
+ {dataset?.name ?? datasetId}
</Badge>
);
})}