🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(web): Add design-system MultiSelectTagInput (#17605)
Ben Bachemedbbf8b25ac4
diff --git a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsxindex 982f39c0f9..805d6643d3 100644--- a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx+++ b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx@@ -3,13 +3,13 @@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 { ChevronDown } from "lucide-react";-import { useScrollGradients } from "@/src/hooks/useScrollGradients";import { cn } from "@/src/utils/tailwind";import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";import { stopScrollPropagation } from "@/src/hooks/stopScrollPropagation";import { InputControl } from "../internal/InputControl/InputControl";+import { InputDropdown } from "../internal/InputDropdown/InputDropdown";type MultiSelectOption<V> = {value: V;@@ -48,8 +48,6 @@ function MultiSelectInputInner<V extends string>(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}>@@ -75,83 +73,72 @@ function MultiSelectInputInner<V extends string>(</PopoverPrimitive.Trigger></InputControl><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);+ <InputDropdown.Content width="popover-trigger">+ <PopoverPrimitive.Content+ align="start"+ sideOffset={4}+ onWheel={stopScrollPropagation()}+ onTouchMove={stopScrollPropagation()}+ >+ <InputDropdown.Root>+ <CommandPrimitive>+ <InputDropdown.Search>+ <CommandPrimitive.Input placeholder={searchPlaceholder} />+ </InputDropdown.Search>+ <InputDropdown.Empty>+ <CommandPrimitive.Empty>+ {emptyMessage}+ </CommandPrimitive.Empty>+ </InputDropdown.Empty>+ <InputDropdown.List>+ <CommandPrimitive.List id={listId}>+ <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;- }+ return (+ <InputDropdown.Option+ key={option.value}+ highlight="aria-selected"+ >+ <CommandPrimitive.Item+ value={option.value}+ keywords={[option.label]}+ 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>+ onValueChange([...value, option.value]);+ }}+ >+ <InputDropdown.OptionContent+ label={option.label}+ title={option.label}+ secondaryLabel={option.secondaryLabel}+ indicator={+ <InputDropdown.CheckIndicator+ checked={isSelected}+ />+ }+ />+ </CommandPrimitive.Item>+ </InputDropdown.Option>+ );+ })}+ </CommandPrimitive.Group>+ </CommandPrimitive.List>+ </InputDropdown.List>+ </CommandPrimitive>+ </InputDropdown.Root>+ </PopoverPrimitive.Content>+ </InputDropdown.Content></PopoverPrimitive.Portal></PopoverPrimitive.Root>);diff --git a/web/src/components/design-system/MultiSelectTagInput/MultiSelectTagInput.stories.tsx b/web/src/components/design-system/MultiSelectTagInput/MultiSelectTagInput.stories.tsxnew file mode 100644index 0000000000..73f275ce9e--- /dev/null+++ b/web/src/components/design-system/MultiSelectTagInput/MultiSelectTagInput.stories.tsx@@ -0,0 +1,205 @@+import { useState } from "react";+import { expect, fn, userEvent, waitFor, within } from "storybook/test";++import preview from "../../../../.storybook/preview";+import { MultiSelectTagInput } from "./MultiSelectTagInput";++const options = [+ { value: "option-1", label: "Option 1" },+ { value: "option-2", label: "Option 2" },+ { value: "option-3", label: "Option 3" },+ { value: "option-4", label: "Option 4" },+];++const manyOptions = Array.from({ length: 20 }, (_, index) => ({+ value: `option-${index + 1}`,+ label: `Option ${index + 1}`,+}));++const meta = preview.meta({+ component: MultiSelectTagInput,+});++export const Default = meta.story({+ args: {+ value: options.slice(0, 3).map((option) => option.value),+ options,+ onValueChange: fn(),+ placeholder: "Select options",+ searchPlaceholder: "Search options...",+ emptyMessage: "No options found.",+ selectAllLabel: "Select All",+ },+ render: (args) => {+ const [value, setValue] = useState(args.value);++ return (+ <MultiSelectTagInput+ {...args}+ value={value}+ onValueChange={(newValue) => {+ setValue(newValue);+ args.onValueChange(newValue);+ }}+ />+ );+ },+});++export const ConstrainedWidth = meta.story({+ args: {+ value: options.slice(0, 3).map((option) => option.value),+ options,+ onValueChange: fn(),+ placeholder: "Select options",+ searchPlaceholder: "Search options...",+ emptyMessage: "No options found.",+ selectAllLabel: "Select All",+ },+ render: (args) => {+ const [value, setValue] = useState(args.value);++ return (+ <div className="w-96">+ <MultiSelectTagInput+ {...args}+ value={value}+ onValueChange={(newValue) => {+ setValue(newValue);+ args.onValueChange(newValue);+ }}+ />+ </div>+ );+ },+});++export const Empty = meta.story({+ args: {+ value: [],+ options: [],+ onValueChange: fn(),+ placeholder: "Select options",+ searchPlaceholder: "Search options...",+ emptyMessage: "No options found.",+ },+});++export const ManySelected = meta.story({+ args: {+ value: manyOptions.map((option) => option.value),+ options: manyOptions,+ onValueChange: fn(),+ placeholder: "Select options",+ searchPlaceholder: "Search options...",+ emptyMessage: "No options found.",+ selectAllLabel: "Select All",+ },+ render: (args) => (+ <div className="w-96">+ <MultiSelectTagInput {...args} />+ </div>+ ),+});++export const TestRemovesTag = meta.story({+ name: "(Test) Removes Tag",+ args: {+ value: ["option-1", "option-2"],+ options,+ onValueChange: fn(),+ placeholder: "Select options",+ searchPlaceholder: "Search options...",+ emptyMessage: "No options found.",+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ canvas.getByRole("button", { name: "Remove Option 1" }),+ );+ await expect(args.onValueChange).toHaveBeenCalledWith(["option-2"]);+ },+});++export const TestSelectsOption = meta.story({+ name: "(Test) Selects Option",+ args: {+ value: ["option-1"],+ options,+ onValueChange: fn(),+ placeholder: "Select options",+ searchPlaceholder: "Search options...",+ emptyMessage: "No options found.",+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ canvas.getByRole("combobox").focus();+ await userEvent.keyboard("{Enter}");+ await userEvent.click(body.getByRole("option", { name: "Option 2" }));+ await expect(args.onValueChange).toHaveBeenCalledWith([+ "option-1",+ "option-2",+ ]);+ },+});++export const TestOverflowBadgePlacement = meta.story({+ name: "(Test) Keeps Overflow Badge Adjacent",+ args: {+ value: manyOptions.map((option) => option.value),+ options: manyOptions,+ onValueChange: fn(),+ placeholder: "Select options",+ searchPlaceholder: "Search options...",+ emptyMessage: "No options found.",+ },+ render: (args) => (+ <div className="w-96">+ <MultiSelectTagInput {...args} />+ </div>+ ),+ play: async ({ canvasElement }) => {+ await waitFor(() => {+ const overflowBadge = canvasElement.querySelector<HTMLElement>(+ "[data-overflow-count]",+ );+ const visibleTags = [+ ...canvasElement.querySelectorAll<HTMLElement>("[data-value]"),+ ].filter((tag) => getComputedStyle(tag).visibility !== "hidden");+ const lastVisibleTag = visibleTags.at(-1);+ const layout = canvasElement.querySelector<HTMLElement>(+ "[data-tag-input-layout]",+ );+ const clearButton = canvasElement.querySelector<HTMLElement>(+ "[data-clear-selection]",+ );++ expect(overflowBadge).not.toBeNull();+ expect(lastVisibleTag).toBeDefined();+ expect(layout).not.toBeNull();+ expect(clearButton).not.toBeNull();++ if (!overflowBadge || !lastVisibleTag || !layout || !clearButton) return;++ const gap =+ overflowBadge.getBoundingClientRect().left -+ lastVisibleTag.getBoundingClientRect().right;+ const clearRightGap =+ layout.getBoundingClientRect().right -+ clearButton.getBoundingClientRect().right;+ const layoutStyles = getComputedStyle(layout);+ const expectedTagGap = Number.parseFloat(layoutStyles.columnGap);+ const expectedClearRightGap = Number.parseFloat(+ layoutStyles.paddingRight,+ );++ expect(Math.abs(gap - expectedTagGap)).toBeLessThanOrEqual(0.5);+ expect(+ Math.abs(clearRightGap - expectedClearRightGap),+ ).toBeLessThanOrEqual(0.5);+ });+ },+});diff --git a/web/src/components/design-system/MultiSelectTagInput/MultiSelectTagInput.tsx b/web/src/components/design-system/MultiSelectTagInput/MultiSelectTagInput.tsxnew file mode 100644index 0000000000..1e7d639305--- /dev/null+++ b/web/src/components/design-system/MultiSelectTagInput/MultiSelectTagInput.tsx@@ -0,0 +1,357 @@+"use client";++import * as React from "react";+import * as PopoverPrimitive from "@radix-ui/react-popover";+import { Command as CommandPrimitive } from "cmdk";+import { ChevronDown, X } from "lucide-react";++import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";+import { stopScrollPropagation } from "@/src/hooks/stopScrollPropagation";+import { cn } from "@/src/utils/tailwind";+import { InputControl } from "../internal/InputControl/InputControl";+import { InputDropdown } from "../internal/InputDropdown/InputDropdown";++type MultiSelectTagOption<V> = {+ value: V;+ label: string;+};++type MultiSelectTagInputProps<V> = {+ value: V[];+ options: MultiSelectTagOption<V>[];+ onValueChange: (newValue: V[]) => void;+ placeholder: string;+ searchPlaceholder: string;+ emptyMessage: string;+ selectAllLabel?: string;+ disabled?: boolean;+ error?: boolean;+ id?: string;+ "aria-describedby"?: string;+ "aria-invalid"?: boolean;+};++export function MultiSelectTagInput<V extends string>({+ value,+ options,+ onValueChange,+ placeholder,+ searchPlaceholder,+ emptyMessage,+ selectAllLabel,+ disabled,+ error,+ id,+ "aria-describedby": ariaDescribedBy,+ "aria-invalid": ariaInvalid,+}: MultiSelectTagInputProps<V>) {+ const container = useLayerContainer("popover");+ const [open, setOpen] = React.useState(false);+ const [fullyVisibleValues, setFullyVisibleValues] = React.useState<Set<V>>(+ new Set(),+ );+ const [trailingHiddenWidth, setTrailingHiddenWidth] = React.useState(0);+ const tagsContainerRef = React.useRef<HTMLDivElement>(null);+ const tagRefs = React.useRef(new Map<V, HTMLSpanElement>());+ const listId = React.useId();+ const selectedOptions = React.useMemo(+ () =>+ value.map((selectedValue) => ({+ value: selectedValue,+ label:+ options.find((option) => option.value === selectedValue)?.label ??+ selectedValue,+ })),+ [options, value],+ );+ const allSelected =+ options.length > 0 &&+ options.every((option) => value.includes(option.value));+ const hiddenOptionCount = selectedOptions.filter(+ (option) => !fullyVisibleValues.has(option.value),+ ).length;+ React.useLayoutEffect(() => {+ const tagsContainer = tagsContainerRef.current;+ if (!tagsContainer) return;++ const recomputeTagVisibility = () => {+ const containerBounds = tagsContainer.getBoundingClientRect();+ const nextValues = new Set<V>();++ tagRefs.current.forEach((tag, optionValue) => {+ const tagBounds = tag.getBoundingClientRect();+ const isFullyVisible =+ tagBounds.left >= containerBounds.left - 1 &&+ tagBounds.right <= containerBounds.right + 1;++ if (isFullyVisible) nextValues.add(optionValue);+ });++ const rightmostVisibleTag = [...tagRefs.current.entries()]+ .filter(([optionValue]) => nextValues.has(optionValue))+ .map(([, tag]) => tag.getBoundingClientRect().right)+ .reduce((rightmost, tagRight) => Math.max(rightmost, tagRight), 0);++ setTrailingHiddenWidth(+ rightmostVisibleTag > 0+ ? Math.max(0, containerBounds.right - rightmostVisibleTag)+ : 0,+ );++ setFullyVisibleValues((currentValues) => {+ if (+ currentValues.size === nextValues.size &&+ [...currentValues].every((optionValue) => nextValues.has(optionValue))+ ) {+ return currentValues;+ }++ return nextValues;+ });+ };++ recomputeTagVisibility();+ const resizeObserver = new ResizeObserver(recomputeTagVisibility);+ resizeObserver.observe(tagsContainer);+ tagRefs.current.forEach((tag) => resizeObserver.observe(tag));+ tagsContainer.addEventListener("scroll", recomputeTagVisibility, {+ passive: true,+ });++ return () => {+ resizeObserver.disconnect();+ tagsContainer.removeEventListener("scroll", recomputeTagVisibility);+ };+ }, [selectedOptions]);++ const changeValue = (newValue: V[]) => {+ if (disabled) return;+ onValueChange(newValue);+ };++ const removeValue = (removedValue: V) => {+ changeValue(+ value.filter((selectedValue) => selectedValue !== removedValue),+ );+ };++ return (+ <PopoverPrimitive.Root+ open={!disabled && open}+ onOpenChange={(newOpen) => {+ if (disabled) return;+ setOpen(newOpen);+ }}+ >+ <InputControl contentLayout="none" error={error} disabled={disabled}>+ <PopoverPrimitive.Trigger asChild>+ <div+ id={id}+ role="combobox"+ aria-controls={listId}+ aria-describedby={ariaDescribedBy}+ aria-expanded={open}+ aria-invalid={ariaInvalid}+ aria-disabled={disabled}+ tabIndex={disabled ? -1 : 0}+ onPointerDown={(event) => {+ if (disabled) event.preventDefault();+ }}+ onClick={(event) => {+ if (disabled) event.preventDefault();+ }}+ onKeyDown={(event) => {+ if (disabled) return;++ if (event.target !== event.currentTarget) return;++ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ setOpen((currentOpen) => !currentOpen);+ return;+ }++ if (event.key === "Backspace" && value.length > 0) {+ event.preventDefault();+ const lastValue = value.at(-1);+ if (lastValue !== undefined) removeValue(lastValue);+ }+ }}+ >+ <div+ data-tag-input-layout+ className="flex h-full min-w-0 items-center gap-1 px-1.5"+ >+ <div+ ref={tagsContainerRef}+ data-tags-container+ className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto whitespace-nowrap [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"+ >+ {selectedOptions.length === 0 ? (+ <span className="text-muted-foreground">{placeholder}</span>+ ) : (+ selectedOptions.map((option) => (+ <span+ key={option.value}+ ref={(tag) => {+ if (tag) {+ tagRefs.current.set(option.value, tag);+ return;+ }++ tagRefs.current.delete(option.value);+ }}+ data-value={option.value}+ title={option.label}+ className={cn(+ "bg-muted flex h-6 max-w-48 min-w-10 shrink items-center gap-1 rounded px-2",+ !fullyVisibleValues.has(option.value) && "invisible",+ )}+ >+ <span className="min-w-0 truncate" title={option.label}>+ {option.label}+ </span>+ <button+ type="button"+ disabled={disabled}+ aria-label={`Remove ${option.label}`}+ className="text-muted-foreground hover:text-foreground -mr-1 flex shrink-0 items-center rounded-sm"+ onClick={(event) => {+ event.stopPropagation();+ removeValue(option.value);+ }}+ >+ <X className="size-3.5" />+ </button>+ </span>+ ))+ )}+ </div>+ {hiddenOptionCount > 0 && (+ <span+ data-overflow-count={hiddenOptionCount}+ aria-label={`${hiddenOptionCount} more selected`}+ title={`${hiddenOptionCount} more selected`}+ className="bg-muted flex h-6 shrink-0 items-center rounded px-1.5 text-xs tabular-nums"+ style={{ transform: `translateX(-${trailingHiddenWidth}px)` }}+ >+ +{hiddenOptionCount}+ </span>+ )}+ {value.length === 0 && (+ <ChevronDown+ aria-hidden="true"+ className="size-4 shrink-0 opacity-50"+ />+ )}+ {value.length > 0 && (+ <button+ type="button"+ disabled={disabled}+ data-clear-selection+ aria-label="Clear selection"+ className="text-muted-foreground hover:text-foreground ml-auto flex shrink-0 items-center rounded-sm px-1"+ onClick={(event) => {+ event.stopPropagation();+ changeValue([]);+ }}+ >+ <X className="size-4" />+ </button>+ )}+ </div>+ </div>+ </PopoverPrimitive.Trigger>+ </InputControl>+ <PopoverPrimitive.Portal container={container}>+ <InputDropdown.Content width="popover-trigger">+ <PopoverPrimitive.Content+ align="start"+ sideOffset={4}+ onWheel={stopScrollPropagation()}+ onTouchMove={stopScrollPropagation()}+ >+ <InputDropdown.Root>+ <CommandPrimitive>+ <InputDropdown.Search>+ <CommandPrimitive.Input placeholder={searchPlaceholder} />+ </InputDropdown.Search>+ <InputDropdown.Empty>+ <CommandPrimitive.Empty>+ {emptyMessage}+ </CommandPrimitive.Empty>+ </InputDropdown.Empty>+ <InputDropdown.List>+ <CommandPrimitive.List id={listId}>+ <CommandPrimitive.Group className="text-foreground overflow-hidden">+ {selectAllLabel && options.length > 0 && (+ <InputDropdown.Option highlight="aria-selected">+ <CommandPrimitive.Item+ value={selectAllLabel}+ onSelect={() =>+ changeValue(+ allSelected+ ? []+ : options.map((option) => option.value),+ )+ }+ >+ <InputDropdown.OptionContent+ label={selectAllLabel}+ title={selectAllLabel}+ indicator={+ <InputDropdown.CheckIndicator+ checked={allSelected}+ />+ }+ />+ </CommandPrimitive.Item>+ </InputDropdown.Option>+ )}+ {selectAllLabel && options.length > 0 && (+ <CommandPrimitive.Separator className="bg-border my-1 h-px" />+ )}+ {options.map((option) => {+ const isSelected = value.includes(option.value);++ return (+ <InputDropdown.Option+ key={option.value}+ highlight="aria-selected"+ >+ <CommandPrimitive.Item+ value={option.value || option.label}+ keywords={[option.label]}+ onSelect={() => {+ if (isSelected) {+ removeValue(option.value);+ return;+ }++ changeValue([...value, option.value]);+ }}+ >+ <InputDropdown.OptionContent+ label={option.label}+ title={option.label}+ indicator={+ <InputDropdown.CheckIndicator+ checked={isSelected}+ />+ }+ />+ </CommandPrimitive.Item>+ </InputDropdown.Option>+ );+ })}+ </CommandPrimitive.Group>+ </CommandPrimitive.List>+ </InputDropdown.List>+ </CommandPrimitive>+ </InputDropdown.Root>+ </PopoverPrimitive.Content>+ </InputDropdown.Content>+ </PopoverPrimitive.Portal>+ </PopoverPrimitive.Root>+ );+}diff --git a/web/src/components/design-system/SelectInput/SelectInput.tsx b/web/src/components/design-system/SelectInput/SelectInput.tsxindex c0dcf49e2b..27189f66e1 100644--- a/web/src/components/design-system/SelectInput/SelectInput.tsx+++ b/web/src/components/design-system/SelectInput/SelectInput.tsx@@ -3,13 +3,11 @@import * as React from "react";import * as SelectPrimitive from "@radix-ui/react-select";-import { assertUnreachable } from "@langfuse/shared";import { useCallback } from "react";import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";-import { Check, ChevronDown, ChevronUp } from "lucide-react";-import { cn } from "@/src/utils/tailwind";-import { useScrollGradients } from "@/src/hooks/useScrollGradients";+import { ChevronDown, ChevronUp } from "lucide-react";import { InputControl } from "../internal/InputControl/InputControl";+import { InputDropdown } from "../internal/InputDropdown/InputDropdown";type SelectOption<V> =| {@@ -64,10 +62,6 @@ function SelectInputInner<V extends string>() {const container = useLayerContainer("popover");const [open, setOpen] = React.useState(false);- const { register, recompute, top, bottom } =- useScrollGradients<React.ComponentRef<typeof SelectPrimitive.Viewport>>(- true,- );const selectedOption = options.flatMap((node) => (isSelectGroup(node) ? node.options : [node])).find((option) => option.value === value);@@ -95,31 +89,31 @@ function SelectInputInner<V extends string>();}- if ("value" in node) {- return (- <SelectPrimitive.SelectItem- key={node.value}- value={node.value}- disabled={node.disabled}- className={cn(- "focus:bg-accent focus: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 data-disabled:opacity-50",- hasPreviousGroup ? "mt-4" : "",- )}- >- <span- className="min-w-0 flex-1 truncate"- title={node.disabled ? node.disabledReason : node.label}+ 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}>- <SelectPrimitive.ItemText>{node.label}</SelectPrimitive.ItemText>- </span>- <SelectPrimitive.ItemIndicator className="ml-auto flex size-3.5 shrink-0 items-center justify-center">- <Check className="size-4" />- </SelectPrimitive.ItemIndicator>- </SelectPrimitive.SelectItem>- );- }-- return assertUnreachable(node);+ <InputDropdown.OptionContent+ label={+ <SelectPrimitive.ItemText>+ {node.label}+ </SelectPrimitive.ItemText>+ }+ title={node.disabled ? node.disabledReason : node.label}+ indicator={+ <SelectPrimitive.ItemIndicator>+ <InputDropdown.CheckIndicator checked />+ </SelectPrimitive.ItemIndicator>+ }+ />+ </SelectPrimitive.SelectItem>+ </InputDropdown.Option>+ </React.Fragment>+ );},[],);@@ -149,46 +143,38 @@ function SelectInputInner<V extends string>(</SelectPrimitive.Trigger></InputControl><SelectPrimitive.Portal container={container}>- <SelectPrimitive.Content- position="popper"- sideOffset={4}- 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-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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-select-trigger-width) min-w-32 overflow-hidden rounded-md border shadow-md"- >- <SelectPrimitive.ScrollUpButton- aria-label="Scroll up"- className="animate-in fade-in-0 fill-mode-both absolute inset-x-0 top-0 z-3 flex h-6 items-center justify-center duration-300 [animation-delay:.5s]"- >- <ChevronUp className="size-4" />- </SelectPrimitive.ScrollUpButton>- <SelectPrimitive.Viewport- 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",- )}- >- {!hasOptions ? (- <div className="text-muted-foreground py-6 text-center text-sm">- {emptyMessage}- </div>- ) : (- options.map((node, index) =>- renderNode(- node,- index > 0 && isSelectGroup(options[index - 1]),- ),- )- )}- </SelectPrimitive.Viewport>- <SelectPrimitive.ScrollDownButton- aria-label="Scroll down"- className="animate-in fade-in-0 fill-mode-both absolute inset-x-0 bottom-0 z-3 flex h-6 items-center justify-center duration-300 [animation-delay:.5s]"- >- <ChevronDown className="size-4" />- </SelectPrimitive.ScrollDownButton>- </SelectPrimitive.Content>+ <InputDropdown.Content width="select-trigger">+ <SelectPrimitive.Content position="popper" sideOffset={4}>+ <SelectPrimitive.ScrollUpButton+ aria-label="Scroll up"+ className="animate-in fade-in-0 fill-mode-both absolute inset-x-0 top-0 z-3 flex h-6 items-center justify-center duration-300 [animation-delay:.5s]"+ >+ <ChevronUp className="size-4" />+ </SelectPrimitive.ScrollUpButton>+ <InputDropdown.List>+ <SelectPrimitive.Viewport>+ {!hasOptions ? (+ <div className="text-muted-foreground py-6 text-center text-sm">+ {emptyMessage}+ </div>+ ) : (+ options.map((node, index) =>+ renderNode(+ node,+ index > 0 && isSelectGroup(options[index - 1]),+ ),+ )+ )}+ </SelectPrimitive.Viewport>+ </InputDropdown.List>+ <SelectPrimitive.ScrollDownButton+ aria-label="Scroll down"+ className="animate-in fade-in-0 fill-mode-both absolute inset-x-0 bottom-0 z-3 flex h-6 items-center justify-center duration-300 [animation-delay:.5s]"+ >+ <ChevronDown className="size-4" />+ </SelectPrimitive.ScrollDownButton>+ </SelectPrimitive.Content>+ </InputDropdown.Content></SelectPrimitive.Portal></SelectPrimitive.Root>);diff --git a/web/src/components/design-system/internal/InputControl/InputControl.tsx b/web/src/components/design-system/internal/InputControl/InputControl.tsxindex a89d366ea0..64107d951b 100644--- a/web/src/components/design-system/internal/InputControl/InputControl.tsx+++ b/web/src/components/design-system/internal/InputControl/InputControl.tsx@@ -4,12 +4,13 @@ import { type LucideIcon } from "lucide-react";import { type ComponentPropsWithoutRef } from "react";const inputControlVariants = cva(- "bg-background ring-offset-background placeholder:text-foreground-tertiary focus-visible:ring-ring disabled:bg-muted/50 h-8 w-full rounded-md border px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-bold focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50",+ "bg-background ring-offset-background placeholder:text-foreground-tertiary focus-visible:ring-ring disabled:bg-muted/50 h-8 w-full rounded-md border text-sm file:border-0 file:bg-transparent file:text-sm file:font-bold focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50",{variants: {contentLayout: {- text: "min-w-14",- spread: "flex min-w-0 items-center justify-between gap-1",+ none: null,+ text: "min-w-14 px-3 py-2",+ spread: "flex min-w-0 items-center justify-between gap-1 px-3 py-2",},trailingAction: {true: "pr-10",@@ -19,6 +20,10 @@ const inputControlVariants = cva(true: "border-destructive [&_svg]:text-destructive",false: "border-input",},+ disabled: {+ true: "bg-muted/50 cursor-not-allowed opacity-50",+ false: null,+ },},defaultVariants: {error: false,@@ -30,8 +35,9 @@ type InputControlProps = Omit<ComponentPropsWithoutRef<typeof Slot>,"className"> & {- contentLayout: "text" | "spread";+ contentLayout: "none" | "text" | "spread";error?: boolean;+ disabled?: boolean;trailingAction?: {label: string;icon: LucideIcon;@@ -50,6 +56,7 @@ type InputControlProps = Omit<export function InputControl({contentLayout,error,+ disabled,trailingAction,...props}: InputControlProps) {@@ -58,6 +65,7 @@ export function InputControl({className={inputControlVariants({contentLayout,error,+ disabled,trailingAction: Boolean(trailingAction),})}{...props}diff --git a/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx b/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsxnew file mode 100644index 0000000000..b690459e4b--- /dev/null+++ b/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx@@ -0,0 +1,142 @@+import { Slot } from "@radix-ui/react-slot";+import { Check, Search as SearchIcon } from "lucide-react";+import { type ComponentPropsWithoutRef, type ReactNode } from "react";++import { useScrollGradients } from "@/src/hooks/useScrollGradients";+import { cn } from "@/src/utils/tailwind";++type SlottedProps = Omit<ComponentPropsWithoutRef<typeof Slot>, "className">;++function Content({+ width,+ ...props+}: SlottedProps & {+ width: "popover-trigger" | "select-trigger";+}) {+ return (+ <Slot+ className={cn(+ "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 min-w-32 overflow-hidden rounded-md border shadow-md outline-hidden",+ width === "popover-trigger"+ ? "w-(--radix-popover-trigger-width)"+ : "data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 w-(--radix-select-trigger-width)",+ )}+ {...props}+ />+ );+}++function Root({ ...props }: SlottedProps) {+ return (+ <Slot+ className="bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md"+ {...props}+ />+ );+}++function Search({ ...props }: SlottedProps) {+ return (+ <div className="flex items-center border-b px-2">+ <SearchIcon className="size-4 shrink-0 opacity-50" />+ <Slot+ 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"+ {...props}+ />+ </div>+ );+}++function Empty({ ...props }: SlottedProps) {+ return <Slot className="py-6 text-center text-sm" {...props} />;+}++function List({ ...props }: SlottedProps) {+ const { register, recompute, top, bottom } =+ useScrollGradients<HTMLDivElement>(true);++ return (+ <div className="relative overflow-hidden">+ <Slot+ ref={register}+ onScroll={recompute}+ className="max-h-96 overflow-auto p-1.5"+ {...props}+ />+ <div+ className={cn(+ "from-popover pointer-events-none absolute inset-x-0 top-0 z-2 h-6 bg-linear-to-b to-transparent",+ top ? "opacity-100" : "opacity-0",+ )}+ />+ <div+ className={cn(+ "from-popover pointer-events-none absolute inset-x-0 bottom-0 z-2 h-6 bg-linear-to-t to-transparent",+ bottom ? "opacity-100" : "opacity-0",+ )}+ />+ </div>+ );+}++function Option({+ highlight,+ ...props+}: SlottedProps & {+ highlight: "aria-selected" | "focus";+}) {+ return (+ <Slot+ className={cn(+ "relative flex w-full cursor-default items-center rounded-sm px-1.5 py-1.5 text-sm outline-hidden select-none",+ highlight === "aria-selected"+ ? "aria-selected:bg-accent aria-selected:text-accent-foreground"+ : "focus:bg-accent focus:text-accent-foreground data-disabled:opacity-50",+ )}+ {...props}+ />+ );+}++function OptionContent({+ label,+ secondaryLabel,+ title,+ indicator,+}: {+ label: ReactNode;+ secondaryLabel?: string;+ title: string;+ indicator: ReactNode;+}) {+ return (+ <>+ <span className="min-w-0 flex-1 truncate" title={title}>+ {label}+ {secondaryLabel && (+ <span className="text-muted-foreground ml-1">{secondaryLabel}</span>+ )}+ </span>+ <span className="flex size-3.5 shrink-0 items-center justify-center">+ {indicator}+ </span>+ </>+ );+}++function CheckIndicator({ checked }: { checked: boolean }) {+ return (+ <Check className={cn("size-4", checked ? "opacity-100" : "opacity-0")} />+ );+}++export const InputDropdown = {+ CheckIndicator,+ Content,+ Empty,+ List,+ Option,+ OptionContent,+ Root,+ Search,+};diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsxindex 7d4a574299..77a184187f 100644--- a/web/src/features/dashboard/components/LatencyChart.tsx+++ b/web/src/features/dashboard/components/LatencyChart.tsx@@ -46,14 +46,7 @@ export const GenerationLatencyChart = ({schedulerId?: string;syncId?: string;}) => {- const {- allModels,- selectedModels,- setSelectedModels,- isAllSelected,- buttonText,- handleSelectAll,- } = useModelSelection(+ const { allModels, selectedModels, setSelectedModels } = useModelSelection(projectId,globalFilterState,fromTimestamp,@@ -164,9 +157,6 @@ export const GenerationLatencyChart = ({allModels={allModels}selectedModels={selectedModels}setSelectedModels={setSelectedModels}- buttonText={buttonText}- isAllSelected={isAllSelected}- handleSelectAll={handleSelectAll}/></div>}diff --git a/web/src/features/dashboard/components/ModelSelector.tsx b/web/src/features/dashboard/components/ModelSelector.tsxindex 4fb79eb9e1..f61059f0b7 100644--- a/web/src/features/dashboard/components/ModelSelector.tsx+++ b/web/src/features/dashboard/components/ModelSelector.tsx@@ -1,107 +1,33 @@-/* eslint-disable @repo/no-abstracted-overlay-trigger */-import { Button } from "@/src/components/ui/button";-import {- InputCommand,- InputCommandEmpty,- InputCommandGroup,- InputCommandInput,- InputCommandItem,- InputCommandList,- InputCommandSeparator,-} from "@/src/components/ui/input-command";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/src/components/ui/popover";+import { MultiSelectTagInput } from "@/src/components/design-system/MultiSelectTagInput/MultiSelectTagInput";import { useAllModels } from "@/src/features/dashboard/components/hooks";-import { cn } from "@/src/utils/tailwind";import { type FilterState } from "@langfuse/shared";import { type ViewVersion } from "@langfuse/shared/query";-import { Check, ChevronsUpDown } from "lucide-react";import { useEffect, useState } from "react";export const ModelSelectorPopover = ({allModels,selectedModels,setSelectedModels,- buttonText,- isAllSelected,- handleSelectAll,}: {allModels: { model: string }[];selectedModels: string[];setSelectedModels: React.Dispatch<React.SetStateAction<string[]>>;- buttonText: string;- isAllSelected: boolean;- handleSelectAll: () => void;-}) => {- const [open, setOpen] = useState(false);-- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <Button- variant="outline"- role="combobox"- aria-expanded={open}- className="w-56 justify-between"- >- {buttonText}- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />- </Button>- </PopoverTrigger>- <PopoverContent className="w-56 p-0">- <InputCommand>- <InputCommandInput placeholder="Search models..." variant="bottom" />- <InputCommandEmpty>No model found.</InputCommandEmpty>- <InputCommandGroup>- <InputCommandItem onSelect={handleSelectAll}>- <Check- className={cn(- "mr-2 h-4 w-4",- isAllSelected ? "opacity-100" : "opacity-0",- )}- />- <span>- <p className="font-bold">Select All</p>- </span>- </InputCommandItem>- <InputCommandSeparator className="my-1" />- <InputCommandList>- {allModels.map((model) => (- <InputCommandItem- key={model.model}- onSelect={() => {- setSelectedModels((prev) =>- prev.includes(model.model)- ? prev.filter((m) => m !== model.model)- : [...prev, model.model],- );- }}- >- <Check- className={cn(- "mr-2 h-4 w-4",- selectedModels.includes(model.model)- ? "opacity-100"- : "opacity-0",- )}- />- {!model.model || model.model === "" ? (- <i>none</i>- ) : (- model.model- )}- </InputCommandItem>- ))}- </InputCommandList>- </InputCommandGroup>- </InputCommand>- </PopoverContent>- </Popover>- );-};+}) => (+ <div className="w-80 max-w-full">+ <MultiSelectTagInput+ value={selectedModels}+ options={allModels.map(({ model }) => ({+ value: model,+ label: model || "none",+ }))}+ onValueChange={setSelectedModels}+ placeholder="Select models"+ searchPlaceholder="Search models..."+ emptyMessage="No model found."+ selectAllLabel="Select All"+ />+ </div>+);export const useModelSelection = (projectId: string,@@ -126,16 +52,6 @@ export const useModelSelection = (const [selectedModels, setSelectedModels] = useState<string[]>([]);const [firstAllModelUpdate, setFirstAllModelUpdate] = useState(true);- const isAllSelected = selectedModels.length === allModels.length;-- const buttonText = isAllSelected- ? "All models"- : `${selectedModels.length} selected`;-- const handleSelectAll = () => {- setSelectedModels(isAllSelected ? [] : [...allModels.map((m) => m.model)]);- };-useEffect(() => {if (firstAllModelUpdate && allModels.length > 0) {setSelectedModels(allModels.slice(0, 10).map((model) => model.model));@@ -147,8 +63,5 @@ export const useModelSelection = (allModels,selectedModels,setSelectedModels,- isAllSelected,- buttonText,- handleSelectAll,};};diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsxindex 500fea6d48..ce71c32ee3 100644--- a/web/src/features/dashboard/components/ModelUsageChart.tsx+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx@@ -51,14 +51,7 @@ export const ModelUsageChart = ({schedulerId?: string;syncId?: string;}) => {- const {- allModels,- selectedModels,- setSelectedModels,- isAllSelected,- buttonText,- handleSelectAll,- } = useModelSelection(+ const { allModels, selectedModels, setSelectedModels } = useModelSelection(projectId,userAndEnvFilterState,fromTimestamp,@@ -364,9 +357,6 @@ export const ModelUsageChart = ({allModels={allModels}selectedModels={selectedModels}setSelectedModels={setSelectedModels}- buttonText={buttonText}- isAllSelected={isAllSelected}- handleSelectAll={handleSelectAll}/></div>}