🪢 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): Improve design-system form components (#19520)
Ben Bachem517ea17b90e7
diff --git a/web/src/components/design-system/AsyncSelectInput/AsyncSelectInput.stories.tsx b/web/src/components/design-system/AsyncSelectInput/AsyncSelectInput.stories.tsxnew file mode 100644index 0000000000..a930d66b24--- /dev/null+++ b/web/src/components/design-system/AsyncSelectInput/AsyncSelectInput.stories.tsx@@ -0,0 +1,137 @@+import { useState } from "react";+import { Hash } from "@langfuse/icons";+import { expect, fn, userEvent, waitFor, within } from "storybook/test";+import preview from "../../../../.storybook/preview";+import { AsyncSelectInput } from "./AsyncSelectInput";++const meta = preview.meta({ component: AsyncSelectInput });++const onSelect = fn();++export const ExternalResults = meta.story({+ name: "(Test) Selected option persists outside external search results",+ render: () => {+ const [search, setSearch] = useState("");+ const [value, setValue] = useState<+ React.ComponentProps<typeof AsyncSelectInput>["value"]+ >({ value: "saved", label: "Saved channel", icon: Hash });+ return (+ <AsyncSelectInput+ aria-label="Channel"+ value={value}+ onValueChange={(next) => {+ setValue(next);+ onSelect(next);+ }}+ placeholder="Select a channel"+ loading={!search ? { message: "Loading options…" } : undefined}+ search={{+ placeholder: "Search channels",+ value: search,+ onValueChange: setSearch,+ }}+ options={+ search+ ? [{ value: "result", label: "Server result", icon: Hash }]+ : []+ }+ />+ );+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ onSelect.mockClear();+ const trigger = canvas.getByRole("combobox");+ await expect(trigger).toHaveTextContent("Saved channel");+ await userEvent.click(trigger);+ await expect(body.getByRole("status")).toHaveTextContent(+ "Loading options…",+ );+ await expect(+ body.queryByText("No options available."),+ ).not.toBeInTheDocument();+ await userEvent.type(+ body.getByPlaceholderText("Search channels"),+ "unrelated query",+ );+ const result = await body.findByRole("option", { name: "Server result" });+ await expect(result).toBeVisible();+ await expect(body.queryByRole("status")).not.toBeInTheDocument();+ await userEvent.keyboard("{ArrowDown}{Enter}");+ await expect(onSelect).toHaveBeenCalledWith({+ value: "result",+ label: "Server result",+ icon: Hash,+ });+ await expect(trigger).toHaveTextContent("Server result");+ await userEvent.click(trigger);+ await expect(body.getByPlaceholderText("Search channels")).toHaveValue("");+ await expect(trigger).toHaveTextContent("Server result");+ },+});++export const CallToActionOption = meta.story({+ name: "(Test) Call to action supports both positions without changing selection",+ args: {+ value: { value: "first", label: "First option" },+ onValueChange: fn(),+ placeholder: "Select an option",+ search: { placeholder: "Search", value: "", onValueChange: fn() },+ options: [+ { value: "first", label: "First option" },+ { value: "second", label: "Second option" },+ ],+ callToActionOption: {+ label: "Create option",+ position: "first",+ onSelect: fn(),+ },+ },+ render: (args) => (+ <div className="flex flex-col gap-2">+ {(["first", "last"] as const).flatMap((position) =>+ [false, true].map((virtualized) => (+ <AsyncSelectInput+ {...args}+ key={`${position}-${virtualized}`}+ aria-label={`${position}-${virtualized}`}+ callToActionOption={+ args.callToActionOption && {+ ...args.callToActionOption,+ position,+ }+ }+ virtualized={virtualized}+ />+ )),+ )}+ </div>+ ),+ play: async ({ args, canvasElement }) => {+ const body = within(canvasElement.ownerDocument.body);+ for (const position of ["first", "last"]) {+ for (const trigger of within(canvasElement).getAllByRole("combobox", {+ name: new RegExp(`^${position}-`),+ })) {+ await userEvent.click(trigger);+ await waitFor(() =>+ expect(+ body.getAllByRole("option").map((option) => option.textContent),+ ).toEqual(+ position === "first"+ ? ["Create option", "First option", "Second option"]+ : ["First option", "Second option", "Create option"],+ ),+ );+ await userEvent.keyboard(+ position === "first" ? "{Home}{Enter}" : "{End}{Enter}",+ );+ await expect(trigger).toHaveTextContent("First option");+ await expect(trigger).toHaveAttribute("aria-expanded", "false");+ }+ }+ await expect(args.callToActionOption?.onSelect).toHaveBeenCalledTimes(4);+ await expect(args.onValueChange).not.toHaveBeenCalled();+ },+});diff --git a/web/src/components/design-system/AsyncSelectInput/AsyncSelectInput.tsx b/web/src/components/design-system/AsyncSelectInput/AsyncSelectInput.tsxnew file mode 100644index 0000000000..6bda185d31--- /dev/null+++ b/web/src/components/design-system/AsyncSelectInput/AsyncSelectInput.tsx@@ -0,0 +1,346 @@+"use client";++import * as React from "react";+import * as PopoverPrimitive from "@radix-ui/react-popover";+import { Command } from "cmdk";+import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual";++import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";+import { stopScrollPropagation } from "@/src/hooks/stopScrollPropagation";+import { cn } from "@/src/utils/tailwind";+import { assertUnreachable } from "@/src/utils/types";+import { type SelectDropdown } from "../SelectDropdown/SelectDropdown";+import { InputControl } from "../internal/InputControl/InputControl";+import { InputDropdown } from "../internal/InputDropdown/InputDropdown";+import { DropdownIndicator } from "../DropdownIndicator/DropdownIndicator";+import { Badge } from "../Badge/Badge";++type SelectedOption<V extends string> = Pick<+ Extract<+ React.ComponentProps<typeof SelectDropdown<V>>["options"][number],+ { value: V }+ >,+ "value" | "label" | "icon"+>;++/** Search and selection are caller-owned; options are rendered without filtering. */+export function AsyncSelectInput<V extends string>({+ value,+ options,+ onValueChange,+ search,+ placeholder,+ loading,+ callToActionOption,+ virtualized = false,+ emptyMessage = "No options available.",+ error,+ muted,+ ref,+ ...triggerProps+}: Pick<+ React.ComponentProps<typeof SelectDropdown<V>>,+ | "options"+ | "emptyMessage"+ | "id"+ | "aria-describedby"+ | "aria-invalid"+ | "aria-label"+ | "disabled"+ | "onBlur"+> & {+ value: SelectedOption<V> | null;+ onValueChange: (option: SelectedOption<V>) => void;+ placeholder: string;+ search: {+ placeholder: string;+ value: string;+ onValueChange: (value: string) => void;+ };+ loading?: { message: string };+ callToActionOption?: {+ label: string;+ position: "first" | "last";+ onSelect: () => void;+ };+ virtualized?: boolean;+ error?: boolean;+ muted?: boolean;+ ref?: React.Ref<HTMLButtonElement>;+}) {+ const container = useLayerContainer("popover");+ const [open, setOpen] = React.useState(false);+ const handleOpenChange = (nextOpen: boolean) => {+ setOpen(nextOpen);+ if (!nextOpen) search.onValueChange("");+ };+ const listId = React.useId();+ const actionId = React.useId();+ const [scrollNode, setScrollNode] = React.useState<HTMLDivElement | null>(+ null,+ );+ const [activeValue, setActiveValue] = React.useState("");+ type Option = Extract<(typeof options)[number], { value: V }>;+ type Row =+ | { type: "heading"; id: string; label: string }+ | { type: "action"; id: string }+ | { type: "option"; option: Option };+ const rows: Row[] = [];+ if (callToActionOption?.position === "first") {+ rows.push({ type: "action", id: actionId });+ }+ for (const node of options) {+ if (node.type === "group") {+ rows.push({ type: "heading", id: node.id, label: node.label });+ rows.push(+ ...node.options.map((option): Row => ({ type: "option", option })),+ );+ } else {+ rows.push({ type: "option", option: node });+ }+ }+ if (callToActionOption?.position === "last") {+ rows.push({ type: "action", id: actionId });+ }+ const activeIndex = rows.findIndex((row) =>+ row.type === "option"+ ? row.option.value === activeValue+ : row.type === "action" && row.id === activeValue,+ );+ const virtualizer = useVirtualizer({+ count: rows.length,+ getScrollElement: () => scrollNode,+ estimateSize: () => 32,+ overscan: 20,+ enabled: virtualized && open,+ rangeExtractor: (range) => {+ const indices = defaultRangeExtractor(range);+ if (activeIndex >= 0 && !indices.includes(activeIndex))+ indices.push(activeIndex);+ return indices.sort((a, b) => a - b);+ },+ });+ const renderOption = (option: Option) => {+ const OptionIcon = option.icon;+ return (+ <InputDropdown.Option+ key={option.value}+ highlight="aria-selected"+ checked={value?.value === option.value}+ >+ <Command.Item+ value={option.value}+ disabled={option.disabled}+ onSelect={() => {+ onValueChange(option);+ handleOpenChange(false);+ }}+ >+ {OptionIcon && <OptionIcon size="base" aria-hidden />}+ <InputDropdown.OptionContent+ type="radio"+ checked={value?.value === option.value}+ label={option.label}+ title={option.disabled ? option.disabledReason : option.label}+ badges={option.badges?.map((badge, index) => (+ <Badge key={index} {...badge} />+ ))}+ />+ </Command.Item>+ </InputDropdown.Option>+ );+ };+ const actionContent = callToActionOption && (+ <InputDropdown.Option highlight="aria-selected">+ <Command.Item+ value={actionId}+ onSelect={() => {+ callToActionOption.onSelect();+ handleOpenChange(false);+ }}+ >+ <span className="truncate" title={callToActionOption.label}>+ {callToActionOption.label}+ </span>+ </Command.Item>+ </InputDropdown.Option>+ );+ const Icon = value?.icon;++ return (+ <PopoverPrimitive.Root open={open} onOpenChange={handleOpenChange}>+ <InputControl+ contentLayout="spread"+ error={error}+ disabled={triggerProps.disabled}+ >+ <PopoverPrimitive.Trigger+ ref={ref}+ type="button"+ role="combobox"+ aria-controls={listId}+ aria-expanded={open}+ title={value?.label}+ {...triggerProps}+ >+ {Icon && <Icon size="base" aria-hidden />}+ <span+ title={value?.label}+ className={cn(+ "min-w-0 flex-1 truncate text-left",+ muted && "text-muted-foreground",+ )}+ >+ {value?.label ?? placeholder}+ </span>+ <DropdownIndicator color={error ? "destructive" : "tertiary"} />+ </PopoverPrimitive.Trigger>+ </InputControl>+ <PopoverPrimitive.Portal container={container}>+ <InputDropdown.Content width="popover-trigger">+ <PopoverPrimitive.Content+ align="start"+ sideOffset={4}+ onWheel={stopScrollPropagation()}+ onTouchMove={stopScrollPropagation()}+ >+ <InputDropdown.Root>+ <Command+ shouldFilter={false}+ value={activeValue}+ onValueChange={setActiveValue}+ onKeyDown={(event) => {+ if (+ !virtualized ||+ !["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)+ )+ return;+ event.preventDefault();+ const selectable = rows.flatMap((row, index) => {+ if (row.type === "action")+ return [{ index, value: row.id }];+ if (row.type === "option" && !row.option.disabled)+ return [{ index, value: row.option.value }];+ return [];+ });+ const current = selectable.findIndex(+ (item) => item.value === activeValue,+ );+ let next = current;+ if (event.key === "Home") next = 0;+ else if (event.key === "End") next = selectable.length - 1;+ else if (event.key === "ArrowDown")+ next = Math.min(current + 1, selectable.length - 1);+ else next = Math.max(current - 1, 0);+ const item = selectable[next];+ if (!item) return;+ setActiveValue(item.value);+ virtualizer.scrollToIndex(item.index, { align: "auto" });+ }}+ >+ <InputDropdown.Search>+ <Command.Input+ placeholder={search.placeholder}+ value={search.value}+ onValueChange={(nextValue) => {+ if (scrollNode) scrollNode.scrollTop = 0;+ search.onValueChange(nextValue);+ }}+ />+ </InputDropdown.Search>+ {!loading && !callToActionOption && (+ <InputDropdown.Empty>+ <Command.Empty>{emptyMessage}</Command.Empty>+ </InputDropdown.Empty>+ )}+ <InputDropdown.List>+ <Command.List+ ref={setScrollNode}+ id={listId}+ aria-busy={Boolean(loading)}+ >+ {virtualized ? (+ <div+ style={{+ height: virtualizer.getTotalSize(),+ position: "relative",+ }}+ >+ {virtualizer.getVirtualItems().map((item) => {+ const row = rows[item.index];+ const content = (() => {+ if (row.type === "option")+ return renderOption(row.option);+ if (row.type === "action") return actionContent;+ if (row.type === "heading")+ return (+ <div className="text-muted-foreground px-2 py-1.5 text-xs font-bold">+ {row.label}+ </div>+ );+ return assertUnreachable(row);+ })();+ return (+ <div+ key={+ row.type === "option"+ ? row.option.value+ : row.id+ }+ ref={virtualizer.measureElement}+ data-index={item.index}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: "100%",+ transform: `translateY(${item.start}px)`,+ }}+ >+ {content}+ </div>+ );+ })}+ </div>+ ) : (+ <>+ {callToActionOption?.position === "first" &&+ actionContent}+ {options.map((node) => {+ const group =+ node.type === "group" ? node : undefined;+ const items =+ node.type === "group" ? node.options : [node];+ const content = items.map(renderOption);+ if (group)+ return (+ <Command.Group+ key={group.id}+ heading={group.label}+ >+ {content}+ </Command.Group>+ );+ return (+ <React.Fragment key={items[0].value}>+ {content}+ </React.Fragment>+ );+ })}+ {callToActionOption?.position === "last" &&+ actionContent}+ </>+ )}+ {loading && (+ <InputDropdown.Loading message={loading.message} />+ )}+ </Command.List>+ </InputDropdown.List>+ </Command>+ </InputDropdown.Root>+ </PopoverPrimitive.Content>+ </InputDropdown.Content>+ </PopoverPrimitive.Portal>+ </PopoverPrimitive.Root>+ );+}diff --git a/web/src/components/design-system/Dialog/Dialog.stories.tsx b/web/src/components/design-system/Dialog/Dialog.stories.tsxindex eb5b114fad..0bf5d5a772 100644--- a/web/src/components/design-system/Dialog/Dialog.stories.tsx+++ b/web/src/components/design-system/Dialog/Dialog.stories.tsx@@ -114,6 +114,48 @@ export const CloseOnly = meta.story({),});+export const DividedBody = meta.story({+ name: "(Test) Divided body",+ render: () => (+ <DialogController+ renderDialog={() => (+ <Dialog title="Divided dialog" closeLabel="Done">+ <Dialog.Body separators="both">+ {Array.from({ length: 30 }, (_, index) => (+ <p key={index}>Review instruction {index + 1}.</p>+ ))}+ </Dialog.Body>+ </Dialog>+ )}+ >+ {({ openDialog }) => <Button text="Open dialog" onClick={openDialog} />}+ </DialogController>+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ await userEvent.click(canvas.getByRole("button", { name: "Open dialog" }));+ const scrollBody = body.getByText("Review instruction 1.").parentElement!;+ const footer = body.getByRole("button", { name: "Done" }).parentElement!;+ await expect(scrollBody).toHaveStyle({+ borderTopWidth: "1px",+ borderBottomWidth: "1px",+ });+ await expect(scrollBody.scrollHeight).toBeGreaterThan(+ scrollBody.clientHeight,+ );+ await expect(scrollBody.getBoundingClientRect().bottom).toBeLessThanOrEqual(+ footer.getBoundingClientRect().top + 1,+ );+ body.getByText("Review instruction 30.").scrollIntoView();+ await waitFor(() => expect(scrollBody.scrollTop).toBeGreaterThan(0));+ await userEvent.click(body.getByRole("button", { name: "Done" }));+ await waitFor(() =>+ expect(body.queryByRole("dialog")).not.toBeInTheDocument(),+ );+ },+});+export const DestructiveAutofocus = meta.story({name: "(Test) Destructive autofocus",render: () => (diff --git a/web/src/components/design-system/Dialog/Dialog.tsx b/web/src/components/design-system/Dialog/Dialog.tsxindex df144337cd..4e989b3808 100644--- a/web/src/components/design-system/Dialog/Dialog.tsx+++ b/web/src/components/design-system/Dialog/Dialog.tsx@@ -221,9 +221,21 @@ function DialogRoot({);}-function DialogBody({ children }: { children: React.ReactNode }) {+function DialogBody({+ children,+ separators = "none",+}: {+ children: React.ReactNode;+ /** Separates the scrolling body from the header and footer with borders. */+ separators?: "none" | "both";+}) {return (- <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4 text-sm leading-relaxed">+ <div+ className={cn(+ "flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4 text-sm leading-relaxed",+ separators === "both" && "border-y",+ )}+ >{children}</div>);diff --git a/web/src/components/design-system/Form/Form.tsx b/web/src/components/design-system/Form/Form.tsxindex c5e1383682..9939ecf717 100644--- a/web/src/components/design-system/Form/Form.tsx+++ b/web/src/components/design-system/Form/Form.tsx@@ -1,7 +1,205 @@-import { type FormHTMLAttributes, type ReactNode } from "react";+import {+ type ComponentProps,+ type FormHTMLAttributes,+ type ReactNode,+} from "react";+import {+ type FieldPath,+ type FieldPathByValue,+ type FieldPathValue,+ type FieldValues,+} from "react-hook-form";import { Button } from "@/src/components/design-system/Button/Button";-import { FormField } from "@/src/components/design-system/FormField/FormField";+import {+ FormField,+ type FormFieldProps,+} from "@/src/components/design-system/FormField/FormField";+import { Input } from "@/src/components/design-system/Input/Input";+import { PasswordInput } from "@/src/components/design-system/PasswordInput/PasswordInput";+import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";++/** Wraps Form.Field with SelectInput and its form bindings. */+function FormSelectInputField<+ TFieldValues extends FieldValues,+ TName extends FieldPathByValue<TFieldValues, string>,+ TTransformedValues extends FieldValues = TFieldValues,+>({+ control,+ name,+ label,+ description,+ registerLabelTooltip,+ required,+ "aria-describedby": describedBy,+ ...inputProps+}: Omit<FormFieldProps<TFieldValues, TName, TTransformedValues>, "children"> &+ Omit<+ ComponentProps<+ typeof SelectInput<Extract<FieldPathValue<TFieldValues, TName>, string>>+ >,+ | "id"+ | "value"+ | "onValueChange"+ | "onBlur"+ | "ref"+ | "error"+ | "aria-invalid"+ >) {+ return (+ <FormField+ control={control}+ name={name}+ label={label}+ description={description}+ registerLabelTooltip={registerLabelTooltip}+ required={required}+ >+ {(field) => (+ <SelectInput<Extract<FieldPathValue<TFieldValues, TName>, string>>+ {...inputProps}+ id={field.id}+ // FieldPathByValue restricts names to string fields; RHF's generic value type does not retain that constraint.+ value={+ field.value as Extract<FieldPathValue<TFieldValues, TName>, string>+ }+ onValueChange={field.onChange}+ onBlur={field.onBlur}+ ref={field.ref}+ aria-describedby={+ [field.inputDescribedById, describedBy].filter(Boolean).join(" ") ||+ undefined+ }+ aria-invalid={Boolean(field.error)}+ error={Boolean(field.error)}+ />+ )}+ </FormField>+ );+}++/** Wraps Form.Field with the default Input and its form bindings. */+function FormInputField<+ TFieldValues extends FieldValues,+ TName extends FieldPath<TFieldValues>,+ TTransformedValues extends FieldValues = TFieldValues,+>({+ control,+ name,+ label,+ description,+ registerLabelTooltip,+ required,+ "aria-describedby": describedBy,+ transformValue,+ ...inputProps+}: Omit<FormFieldProps<TFieldValues, TName, TTransformedValues>, "children"> &+ Omit<+ ComponentProps<typeof Input>,+ | "id"+ | "name"+ | "value"+ | "defaultValue"+ | "onChange"+ | "onBlur"+ | "ref"+ | "error"+ | "aria-invalid"+ > & {+ /** Normalizes incoming text before updating form state. */+ transformValue?: (value: string) => string;+ }) {+ return (+ <FormField+ control={control}+ name={name}+ label={label}+ description={description}+ registerLabelTooltip={registerLabelTooltip}+ required={required}+ >+ {(field) => (+ <Input+ {...inputProps}+ id={field.id}+ name={field.name}+ value={field.value}+ onChange={(event) => {+ const value = event.target.value;+ field.onChange(transformValue ? transformValue(value) : value);+ }}+ onBlur={field.onBlur}+ ref={field.ref}+ required={required}+ aria-describedby={+ [field.inputDescribedById, describedBy].filter(Boolean).join(" ") ||+ undefined+ }+ aria-invalid={Boolean(field.error)}+ error={Boolean(field.error)}+ />+ )}+ </FormField>+ );+}++/** Wraps Form.Field with PasswordInput and its form bindings. */+function FormPasswordInputField<+ TFieldValues extends FieldValues,+ TName extends FieldPath<TFieldValues>,+ TTransformedValues extends FieldValues = TFieldValues,+>({+ control,+ name,+ label,+ description,+ registerLabelTooltip,+ required,+ "aria-describedby": describedBy,+ ...inputProps+}: Omit<FormFieldProps<TFieldValues, TName, TTransformedValues>, "children"> &+ Omit<+ ComponentProps<typeof PasswordInput>,+ | "id"+ | "name"+ | "value"+ | "defaultValue"+ | "onChange"+ | "onBlur"+ | "ref"+ | "error"+ | "aria-invalid"+ >) {+ return (+ <FormField+ control={control}+ name={name}+ label={label}+ description={description}+ registerLabelTooltip={registerLabelTooltip}+ required={required}+ >+ {(field) => (+ <PasswordInput+ {...inputProps}+ id={field.id}+ name={field.name}+ value={field.value}+ onChange={field.onChange}+ onBlur={field.onBlur}+ ref={field.ref}+ required={required}+ aria-describedby={+ [field.inputDescribedById, describedBy].filter(Boolean).join(" ") ||+ undefined+ }+ aria-invalid={Boolean(field.error)}+ error={Boolean(field.error)}+ />+ )}+ </FormField>+ );+}export type FormAction = {id: string;@@ -80,4 +278,7 @@ function FormRoot({export const Form = Object.assign(FormRoot, {Field: FormField,+ InputField: FormInputField,+ PasswordInputField: FormPasswordInputField,+ SelectInputField: FormSelectInputField,});diff --git a/web/src/components/design-system/FormField/FormField.stories.tsx b/web/src/components/design-system/FormField/FormField.stories.tsxindex 847241e1d0..f74b6231d8 100644--- a/web/src/components/design-system/FormField/FormField.stories.tsx+++ b/web/src/components/design-system/FormField/FormField.stories.tsx@@ -1,4 +1,4 @@-import { useEffect } from "react";+import { useEffect, type ComponentProps } from "react";import { useForm } from "react-hook-form";import { expect, within } from "storybook/test";@@ -6,12 +6,13 @@ import preview from "../../../../.storybook/preview";import { CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";import { Input } from "@/src/components/design-system/Input/Input";import { FormField } from "./FormField";+import { Form } from "../Form/Form";function FormFieldExample({description,error,}: {- description?: string;+ description?: ComponentProps<typeof FormField>["description"];error?: string;}) {const form = useForm<{ name: string }>({@@ -55,23 +56,64 @@ const meta = preview.meta({export const Default = meta.story({});+export const RichDescription = meta.story({+ name: "(Test) Rich description with error",+ args: {+ description: [+ { type: "text", text: "Use the " },+ { type: "code", text: "name" },+ { type: "text", text: " field. " },+ { type: "link", text: "Learn more", href: "https://langfuse.com/docs" },+ { type: "text", text: " " },+ { type: "strong", text: "Required." },+ ],+ error: "Name is required.",+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByLabelText("Name");+ const code = canvas.getByText("name", { selector: "code" });+ const description = code.closest("p");+ const error = await canvas.findByText("Name is required.");++ await expect(description).toHaveTextContent(+ "Use the name field. Learn more Required.",+ );+ await expect(input).toHaveAttribute(+ "aria-describedby",+ `${error.id} ${description?.id}`,+ );+ },+});+export const Standalone = meta.story({- name: "(Test) Standalone",+ name: "(Test) Standalone with rich description",render: () => (- <FormField- label="Preview date range"- description="Only affects this preview."+ <Form.Field+ label="Webhook secret"+ description={[+ { type: "text", text: "Use the " },+ { type: "code", text: "x-langfuse-signature" },+ { type: "text", text: " header." },+ ]}>{(field) => (- <Input id={field.id} aria-describedby={field.inputDescribedById} />+ <Input+ id={field.id}+ aria-describedby={field.inputDescribedById}+ readOnly+ value="secret"+ />)}- </FormField>+ </Form.Field>),play: async ({ canvasElement }) => {const canvas = within(canvasElement);- const input = canvas.getByLabelText("Preview date range");- const description = canvas.getByText("Only affects this preview.");- await expect(input).toHaveAttribute("aria-describedby", description.id);+ const description = canvas.getByText("x-langfuse-signature").closest("p");+ await expect(canvas.getByLabelText("Webhook secret")).toHaveAttribute(+ "aria-describedby",+ description?.id,+ );},});diff --git a/web/src/components/design-system/FormField/FormField.tsx b/web/src/components/design-system/FormField/FormField.tsxindex 9c0938a237..dbe01b8d78 100644--- a/web/src/components/design-system/FormField/FormField.tsx+++ b/web/src/components/design-system/FormField/FormField.tsx@@ -1,6 +1,6 @@"use client";-import { Info } from "@langfuse/icons";+import { Info, SquareArrowOutUpRight } from "@langfuse/icons";import { useId, type ComponentProps, type ReactElement } from "react";import {Controller,@@ -12,6 +12,16 @@ import {} from "react-hook-form";import { type CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";+import { assertUnreachable } from "@/src/utils/types";++type FormFieldDescription =+ | string+ | readonly (+ | { type: "text"; text: string }+ | { type: "code"; text: string }+ | { type: "link"; text: string; href: string }+ | { type: "strong"; text: string }+ )[];type TooltipTriggerPropsGetter = Parameters<ComponentProps<typeof CustomTooltip>["children"]@@ -30,7 +40,7 @@ export type FormFieldProps<inputDescribedById: string | undefined;},) => ReactElement;- description?: string;+ description?: FormFieldDescription;label: string;name: TName;registerLabelTooltip?: TooltipTriggerPropsGetter;@@ -44,12 +54,69 @@ type StandaloneFormFieldProps = {id: string;inputDescribedById: string | undefined;}) => ReactElement;- description?: string;+ description?: FormFieldDescription;label: string;registerLabelTooltip?: TooltipTriggerPropsGetter;required?: boolean;};+function FormFieldDescription({+ description,+ id,+}: {+ description: FormFieldDescription;+ id: string;+}) {+ return (+ <p id={id} className="text-muted-foreground text-sm">+ {typeof description === "string"+ ? description+ : description.map((element, index) => {+ if (element.type === "text") {+ return element.text;+ }+ if (element.type === "code") {+ return (+ <code+ key={index}+ className="bg-muted rounded-md px-1 py-px font-mono text-xs"+ >+ {element.text}+ </code>+ );+ }+ if (element.type === "link") {+ return (+ <a+ key={index}+ className="text-link hover:text-link-hover underline underline-offset-2"+ href={element.href}+ target="_blank"+ rel="noopener noreferrer"+ >+ {element.text}+ <SquareArrowOutUpRight+ aria-hidden+ size="sm"+ color="muted"+ __rawClassName="ml-0.75 inline-block align-[-1px]"+ />+ </a>+ );+ }+ if (element.type === "strong") {+ return (+ <strong key={index} className="text-foreground font-bold">+ {element.text}+ </strong>+ );+ }+ return assertUnreachable(element);+ })}+ </p>+ );+}+function FormFieldLayout({label,controlId,@@ -63,7 +130,7 @@ function FormFieldLayout({}: {label: string;controlId: string;- description?: string;+ description?: FormFieldDescription;descriptionId: string;errorMessage?: string;errorId: string;@@ -101,9 +168,7 @@ function FormFieldLayout({) : null}</div>{description ? (- <p id={descriptionId} className="text-muted-foreground text-sm">- {description}- </p>+ <FormFieldDescription id={descriptionId} description={description} />) : null}</div>);@@ -128,7 +193,11 @@ export function FormField<const controlId = `${id}-control`;const descriptionId = `${id}-description`;const errorId = `${id}-error`;- const { label, description, registerLabelTooltip, required } = props;+ const { label, registerLabelTooltip, required } = props;+ const description =+ props.description !== undefined && props.description.length > 0+ ? props.description+ : undefined;if (props.control) {const { control, name, children } = props;diff --git a/web/src/components/design-system/Input/Input.stories.tsx b/web/src/components/design-system/Input/Input.stories.tsxindex c194da39d5..d4c36569a3 100644--- a/web/src/components/design-system/Input/Input.stories.tsx+++ b/web/src/components/design-system/Input/Input.stories.tsx@@ -1,4 +1,5 @@import { expect, userEvent, within } from "storybook/test";+import { Search } from "@langfuse/icons";import preview from "../../../../.storybook/preview";import { Input } from "./Input";@@ -66,3 +67,77 @@ export const TestAcceptsText = meta.story({await expect(input).toHaveValue("production/evaluations");},});++export const WithIconPrefix = meta.story({+ args: {+ "aria-label": "Search datasets",+ prefix: { icon: Search },+ placeholder: "Search datasets",+ },+});++export const WithLabelAndIconPrefix = meta.story({+ args: {+ "aria-label": "Search datasets",+ prefix: { label: "Search", icon: Search },+ placeholder: "Dataset name",+ },+});++export const WithPrefixes = meta.story({+ name: "(Test) Prefix clicks focus the editable value",+ args: {+ "aria-label": "Webhook URL",+ prefix: { label: "POST" },+ valuePrefix: "https://",+ placeholder: "example.com/webhook",+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("textbox", { name: "Webhook URL" });+ await userEvent.click(canvas.getByText("POST"));+ await expect(input).toHaveFocus();+ await userEvent.tab();+ await userEvent.click(canvas.getByText("https://"));+ await expect(input).toHaveFocus();+ await userEvent.type(input, "example.com/webhook");+ await expect(input).toHaveValue("example.com/webhook");+ },+});++export const WithValuePrefix = meta.story({+ args: {+ "aria-label": "Repository dispatch URL",+ valuePrefix: "https://",+ placeholder: "api.github.com/repos/owner/repo/dispatches",+ },+});++export const WithPrefix = meta.story({+ args: {+ "aria-label": "Webhook URL",+ prefix: { label: "POST" },+ placeholder: "https://example.com/webhook",+ },+});++export const InvalidWithPrefixes = meta.story({+ args: {+ "aria-label": "Webhook URL",+ prefix: { label: "POST" },+ valuePrefix: "https://",+ defaultValue: "not a url",+ error: true,+ "aria-invalid": true,+ },+});++export const DisabledWithPrefixes = meta.story({+ args: {+ "aria-label": "Webhook URL",+ prefix: { label: "POST" },+ valuePrefix: "https://",+ defaultValue: "example.com/webhook",+ disabled: true,+ },+});diff --git a/web/src/components/design-system/Input/Input.tsx b/web/src/components/design-system/Input/Input.tsxindex aeb3cb7e7b..523fb39d83 100644--- a/web/src/components/design-system/Input/Input.tsx+++ b/web/src/components/design-system/Input/Input.tsx@@ -1,6 +1,47 @@-import { type InputHTMLAttributes, type Ref } from "react";+import { type ComponentProps, type InputHTMLAttributes, type Ref } from "react";+import { cva } from "class-variance-authority";import { InputControl } from "../internal/InputControl/InputControl";+const inputVariants = cva(+ "placeholder:text-muted-foreground text-sm disabled:cursor-not-allowed",+ {+ variants: {+ valuePrefixed: {+ true: "h-full min-w-0 flex-1 border-0 bg-transparent p-0 shadow-none outline-hidden focus:ring-0",+ false: null,+ },+ layout: {+ block: null,+ inline: "field-sizing-content",+ },+ },+ },+);++const valuePrefixControlVariants = cva(+ "flex min-w-0 cursor-text items-center overflow-hidden px-3",+ {+ variants: {+ standalone: {+ true: "focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",+ false: null,+ },+ error: {+ true: null,+ false: null,+ },+ },+ compoundVariants: [+ {+ standalone: true,+ error: true,+ className:+ "focus-within:ring-destructive/40 focus-within:ring-offset-0",+ },+ ],+ },+);+type InputProps = Pick<InputHTMLAttributes<HTMLInputElement>,| "aria-describedby"@@ -35,6 +76,10 @@ type InputProps = Pick<> & {allowPasswordManager?: boolean;error?: boolean;+ /** Shaded label and/or decorative icon before the editable value. */+ prefix?: ComponentProps<typeof InputControl>["prefix"];+ /** Uneditable text displayed as part of the value, e.g. https://. */+ valuePrefix?: string;/*** `inline` sits within a sentence and grows and shrinks with its value;* place it in a `w-fit` container.@@ -47,17 +92,58 @@ export function Input({allowPasswordManager,error,layout = "block",+ prefix,+ valuePrefix,ref,+ disabled,...props}: InputProps) {+ if (valuePrefix === undefined) {+ return (+ <InputControl+ contentLayout="text"+ error={error}+ disabled={disabled}+ prefix={prefix}+ >+ <input+ {...props}+ className={inputVariants({ valuePrefixed: false, layout })}+ {...(!allowPasswordManager && { "data-1p-ignore": true })}+ ref={ref}+ disabled={disabled}+ />+ </InputControl>+ );+ }+return (- <InputControl contentLayout="text" error={error}>- <input- {...props}- className={layout === "inline" ? "field-sizing-content" : undefined}- {...(!allowPasswordManager && { "data-1p-ignore": true })}- ref={ref}- />+ <InputControl+ contentLayout="none"+ error={error}+ disabled={disabled}+ prefix={prefix}+ >+ <div+ className={valuePrefixControlVariants({ error, standalone: !prefix })}+ onMouseDown={(event) => {+ const input = event.currentTarget.querySelector("input");+ if (event.target === input) return;+ event.preventDefault();+ input?.focus();+ }}+ >+ <span className="text-foreground-secondary shrink-0 pr-0.5">+ {valuePrefix}+ </span>+ <input+ {...props}+ className={inputVariants({ valuePrefixed: true, layout })}+ {...(!allowPasswordManager && { "data-1p-ignore": true })}+ ref={ref}+ disabled={disabled}+ />+ </div></InputControl>);}diff --git a/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx b/web/src/components/design-system/SelectDropdown/SelectDropdown.tsxindex 2b5adbb154..d60ba2648e 100644--- a/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx+++ b/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx@@ -9,6 +9,7 @@ import { CustomTooltip } from "@/src/components/design-system/CustomTooltip/Custimport { InputDropdown } from "@/src/components/design-system/internal/InputDropdown/InputDropdown";type SelectOption<V> = {+ type?: "option";value: V;label: string;icon?: IconComponent;@@ -37,7 +38,7 @@ type SelectNode<V> =function isSelectGroup<V>(node: SelectNode<V>,): node is Extract<SelectNode<V>, { type: "group" }> {- return "type" in node && node.type === "group";+ return node.type === "group";}type TriggerControls = {@@ -95,7 +96,12 @@ export function SelectDropdown<V extends string>({ref?: React.Ref<HTMLButtonElement>;} & Pick<React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>,- "id" | "aria-describedby" | "aria-invalid" | "aria-label" | "disabled"+ | "id"+ | "aria-describedby"+ | "aria-invalid"+ | "aria-label"+ | "disabled"+ | "onBlur">) {const container = useLayerContainer("popover");const selectedOption = optionsdiff --git a/web/src/components/design-system/SelectInput/SelectInput.tsx b/web/src/components/design-system/SelectInput/SelectInput.tsxindex de8890d7df..c845646af2 100644--- a/web/src/components/design-system/SelectInput/SelectInput.tsx+++ b/web/src/components/design-system/SelectInput/SelectInput.tsx@@ -1,22 +1,14 @@"use client";import * as React from "react";-import * as PopoverPrimitive from "@radix-ui/react-popover";-import { Command as CommandPrimitive } from "cmdk";+import { defaultFilter } from "cmdk";-import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";import { SelectDropdown } from "../SelectDropdown/SelectDropdown";-import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";-import { Badge } from "../Badge/Badge";-import { stopScrollPropagation } from "@/src/hooks/stopScrollPropagation";+import { AsyncSelectInput } from "../AsyncSelectInput/AsyncSelectInput";+import { DropdownIndicator } from "../DropdownIndicator/DropdownIndicator";import { InputControl } from "../internal/InputControl/InputControl";-import { InputDropdown } from "../internal/InputDropdown/InputDropdown";import { cn } from "@/src/utils/tailwind";-type SelectInputNode<V extends string> = React.ComponentProps<- typeof SelectDropdown<V>->["options"][number];-type SelectInputProps<V extends string> = Pick<React.ComponentProps<typeof SelectDropdown<V>>,| "value"@@ -28,6 +20,7 @@ type SelectInputProps<V extends string> = Pick<| "aria-invalid"| "aria-label"| "disabled"+ | "onBlur"> & {placeholder: string;search?: { placeholder: string };@@ -35,19 +28,13 @@ type SelectInputProps<V extends string> = Pick<muted?: boolean;};-function isSelectGroup<V extends string>(- node: SelectInputNode<V>,-): node is Extract<SelectInputNode<V>, { type: "group" }> {- return "type" in node && node.type === "group";-}-function SelectInputInner<V extends string>({value,options,onValueChange,placeholder,- emptyMessage = "No options available.",+ emptyMessage,search,error,muted,@@ -55,123 +42,60 @@ function SelectInputInner<V extends string>(}: SelectInputProps<V>,ref: React.ForwardedRef<HTMLButtonElement>,) {- const container = useLayerContainer("popover");- const [open, setOpen] = React.useState(false);- const selectedOption = options- .flatMap((node) => (isSelectGroup(node) ? node.options : [node]))- .find((option) => option.value === value);- const listId = React.useId();+ const [searchValue, setSearchValue] = React.useState("");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={cn(- "min-w-0 flex-1 truncate text-left",- muted && "text-muted-foreground",- )}- title={selectedOption?.label}- >- {selectedOption?.label ?? placeholder}- </span>- <DropdownIndicator color={error ? "destructive" : "tertiary"} />- </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={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- }- badges={option.badges?.map((badge, index) => (- <Badge key={index} {...badge} />- ))}- />- </CommandPrimitive.Item>- </InputDropdown.Option>- ));+ const flatOptions = options.flatMap((node) =>+ node.type === "group" ? node.options : [node],+ );+ const selectedOption = flatOptions.find((option) => option.value === value);+ // cmdk exports this function, but types it as its optional `filter` prop.+ const rank = (option: (typeof flatOptions)[number]) =>+ defaultFilter!(option.value.trim(), searchValue.trim(), [+ option.label.trim(),+ ]);+ const filteredOptions = searchValue.trim()+ ? options+ .flatMap<+ React.ComponentProps<typeof SelectDropdown<V>>["options"][number]+ >((node) => {+ if (node.type === "group") {+ const items = node.options+ .filter((option) => rank(option) > 0)+ .sort((a, b) => rank(b) - rank(a));+ return items.length > 0 ? [{ ...node, options: items }] : [];+ }+ return rank(node) > 0 ? [node] : [];+ })+ .sort((a, b) => {+ const aRank =+ a.type === "group" ? Math.max(...a.options.map(rank)) : rank(a);+ const bRank =+ b.type === "group" ? Math.max(...b.options.map(rank)) : rank(b);+ return bRank - aRank;+ })+ : options;- 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>+ return (+ <AsyncSelectInput+ {...triggerProps}+ ref={ref}+ value={selectedOption ?? null}+ options={filteredOptions}+ onValueChange={(option) => onValueChange(option.value)}+ placeholder={placeholder}+ emptyMessage={emptyMessage}+ search={{+ ...search,+ value: searchValue,+ onValueChange: setSearchValue,+ }}+ error={error}+ muted={muted}+ />);}+return (<SelectDropdownvalue={value}@@ -205,12 +129,10 @@ type SelectInputComponent = {<V extends string>(props: SelectInputProps<V> & React.RefAttributes<HTMLButtonElement>,): React.ReactElement | null;-displayName?: string;};export const SelectInput = React.forwardRef(SelectInputInner,) as SelectInputComponent;-SelectInput.displayName = "SelectInput";diff --git a/web/src/components/design-system/internal/InputControl/InputControl.tsx b/web/src/components/design-system/internal/InputControl/InputControl.tsxindex b4687151a2..682ff8d245 100644--- a/web/src/components/design-system/internal/InputControl/InputControl.tsx+++ b/web/src/components/design-system/internal/InputControl/InputControl.tsx@@ -4,14 +4,35 @@ import { type IconComponent } from "@langfuse/icons";import { type ComponentPropsWithoutRef } from "react";import { cn } from "@/src/utils/tailwind";+const inputContentVariants = cva("", {+ variants: {+ contentLayout: {+ 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",+ },+ },+});++const inputSlotVariants = cva(+ "placeholder:text-muted-foreground text-sm disabled:cursor-not-allowed",+ {+ variants: {+ prefixed: {+ true: "h-full min-w-0 flex-1 border-0 bg-transparent py-0 shadow-none outline-hidden focus:ring-0",+ false: null,+ },+ },+ },+);+const inputControlVariants = cva("bg-background ring-offset-background placeholder:text-muted-foreground 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: {- 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",+ prefixed: {+ true: "flex min-w-0 items-center overflow-hidden focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",+ false: null,},trailingAction: {true: "pr-10",@@ -29,16 +50,27 @@ const inputControlVariants = cva(defaultVariants: {error: false,},+ compoundVariants: [+ {+ prefixed: true,+ error: true,+ className:+ "focus-within:ring-destructive/40 focus-within:ring-offset-0",+ },+ ],},);type InputControlProps = Omit<ComponentPropsWithoutRef<typeof Slot>,- "className"+ "className" | "prefix"> & {contentLayout: "none" | "text" | "spread";error?: boolean;disabled?: boolean;+ prefix?:+ | { label: string; icon?: IconComponent }+ | { label?: never; icon: IconComponent };trailingAction?: {label: string;icon: IconComponent;@@ -49,55 +81,77 @@ type InputControlProps = Omit<};/**- * Applies the shared form-control appearance directly to one interactive child.- * Use explicit variants for root layout differences. The control owns the- * positioning and spacing of an optional trailing action; specialized inputs- * own the action's behavior and inner content.+ * Owns shared form-control styling and optional prefix and action layout.+ * Specialized inputs own the interactive child's behavior.*/export function InputControl({contentLayout,error,disabled,trailingAction,+ prefix,...props}: InputControlProps) {- const control = (- <Slot- className={cn(- inputControlVariants({- contentLayout,- error,- disabled,- trailingAction: Boolean(trailingAction),- }),- )}- {...props}- />+ const controlClassName = inputControlVariants({+ prefixed: prefix !== undefined,+ error,+ disabled,+ trailingAction: Boolean(trailingAction),+ });+ const PrefixIcon = prefix?.icon;+ const slotClassName = cn(+ inputContentVariants({ contentLayout }),+ inputSlotVariants({ prefixed: prefix !== undefined }),+ !prefix && controlClassName,);- if (!trailingAction) return control;+ if (!prefix && !trailingAction) {+ return <Slot className={slotClassName} {...props} />;+ }- const TrailingActionIcon = trailingAction.icon;+ const TrailingActionIcon = trailingAction?.icon;return (- <div className="relative">- {control}- <button- type="button"- aria-label={trailingAction.label}- aria-pressed={trailingAction.pressed}- disabled={trailingAction.disabled}- // Keep the action out of the tab order so Tab moves between inputs.- tabIndex={-1}- className="absolute top-1/2 right-3 flex -translate-y-1/2 cursor-pointer items-center justify-center disabled:cursor-not-allowed"- onClick={trailingAction.onClick}- >- <TrailingActionIcon- aria-hidden="true"- size="base"- color={error ? "destructive" : "muted"}- />- </button>+ <div+ className={cn("relative", prefix && controlClassName)}+ onMouseDown={(event) => {+ if (!prefix) return;+ const input = event.currentTarget.querySelector("input");+ if (event.target === input) return;+ if (event.target instanceof Element && event.target.closest("button"))+ return;+ if (!input) return;+ event.preventDefault();+ input.focus();+ }}+ >+ {prefix && (+ <span className="bg-muted text-muted-foreground border-input flex h-full shrink-0 items-center gap-1.5 border-r px-2.5 font-mono text-xs">+ {PrefixIcon && (+ <PrefixIcon aria-hidden="true" size="base" color="muted" />+ )}+ {prefix.label}+ </span>+ )}+ <Slot className={slotClassName} {...props} />+ {trailingAction && TrailingActionIcon && (+ <button+ type="button"+ aria-label={trailingAction.label}+ aria-pressed={trailingAction.pressed}+ disabled={trailingAction.disabled}+ // Keep the action out of the tab order so Tab moves between inputs.+ tabIndex={-1}+ className="absolute top-1/2 right-3 flex -translate-y-1/2 cursor-pointer items-center justify-center disabled:cursor-not-allowed"+ onClick={trailingAction.onClick}+ >+ <TrailingActionIcon+ aria-hidden="true"+ size="base"+ color={error ? "destructive" : "muted"}+ />+ </button>+ )}</div>);}diff --git a/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx b/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsxindex 42f824b97c..dd7df6e874 100644--- a/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx+++ b/web/src/components/design-system/internal/InputDropdown/InputDropdown.tsx@@ -1,5 +1,5 @@import { Slot } from "@radix-ui/react-slot";-import { Check, Search as SearchIcon } from "@langfuse/icons";+import { Check, LoaderCircle, Search as SearchIcon } from "@langfuse/icons";import { type ComponentPropsWithoutRef, type ReactNode, useMemo } from "react";import { useScrollGradients } from "@/src/hooks/useScrollGradients";@@ -102,6 +102,25 @@ function Option({);}+function Loading({ message }: { message: string }) {+ return (+ <Option highlight="aria-selected">+ <div aria-disabled="true">+ <span role="status" className="contents">+ <span className="flex w-3.5 shrink-0 items-center justify-center">+ <LoaderCircle+ size="base"+ aria-hidden+ __rawClassName="animate-spin"+ />+ </span>+ {message}+ </span>+ </div>+ </Option>+ );+}+function OptionContent({label,secondaryLabel,@@ -197,6 +216,7 @@ export const InputDropdown = {Content,Empty,List,+ Loading,Option,OptionContent,Root,diff --git a/web/src/features/monitors/automations/components/DividedDialogBody.tsx b/web/src/features/monitors/automations/components/DividedDialogBody.tsxdeleted file mode 100644index 4ba296d181..0000000000--- a/web/src/features/monitors/automations/components/DividedDialogBody.tsx+++ /dev/null@@ -1,10 +0,0 @@-import { type ReactNode } from "react";--/** DividedDialogBody is a scrolling dialog body set off from the header and footer by borders. */-export function DividedDialogBody({ children }: { children: ReactNode }) {- return (- <div className="flex min-h-0 flex-1 flex-col overflow-y-auto border-y p-4">- {children}- </div>- );-}diff --git a/web/src/features/monitors/automations/components/FieldHelp.tsx b/web/src/features/monitors/automations/components/FieldHelp.tsxdeleted file mode 100644index 2aeb4c4c3a..0000000000--- a/web/src/features/monitors/automations/components/FieldHelp.tsx+++ /dev/null@@ -1,16 +0,0 @@-import { type ReactNode } from "react";--/** FieldHelp is help text with inline code or links, rendered below a field whose input lists `id` in aria-describedby. */-export function FieldHelp({- id,- children,-}: {- id: string;- children: ReactNode;-}) {- return (- <p id={id} className="text-muted-foreground text-sm">- {children}- </p>- );-}diff --git a/web/src/features/monitors/automations/components/FieldWithHelp.tsx b/web/src/features/monitors/automations/components/FieldWithHelp.tsxdeleted file mode 100644index b326e199fd..0000000000--- a/web/src/features/monitors/automations/components/FieldWithHelp.tsx+++ /dev/null@@ -1,6 +0,0 @@-import { type ReactNode } from "react";--/** FieldWithHelp keeps a form field and the FieldHelp below it as close together as the field's own help text. */-export function FieldWithHelp({ children }: { children: ReactNode }) {- return <div className="flex flex-col gap-2">{children}</div>;-}diff --git a/web/src/features/monitors/automations/components/GitHubDispatchActionFields.tsx b/web/src/features/monitors/automations/components/GitHubDispatchActionFields.tsxindex 2458a8165f..8496ed140d 100644--- a/web/src/features/monitors/automations/components/GitHubDispatchActionFields.tsx+++ b/web/src/features/monitors/automations/components/GitHubDispatchActionFields.tsx@@ -1,17 +1,8 @@-import { useId } from "react";import { type UseFormReturn } from "react-hook-form";import { Form } from "@/src/components/design-system/Form/Form";-import { Input } from "@/src/components/design-system/Input/Input";-import { PasswordInput } from "@/src/components/design-system/PasswordInput/PasswordInput";import { type MonitorAutomationFormValues } from "../helpers/monitorAutomationFormSchema";-import { InlineCode } from "./InlineCode";-import { describedBy } from "../helpers/describedBy";import { stripUrlScheme } from "../helpers/stripUrlScheme";-import { FieldHelp } from "./FieldHelp";-import { FieldWithHelp } from "./FieldWithHelp";-import { HelpLink } from "./HelpLink";-import { PrefixedInput } from "./PrefixedInput";const dispatchDocsUrl ="https://docs.github.com/en/rest/repos/repos#create-a-repository-dispatch-event";@@ -24,103 +15,47 @@ export function GitHubDispatchActionFields({}: {form: UseFormReturn<MonitorAutomationFormValues>;}) {- const urlHelpId = useId();- const eventTypeHelpId = useId();- const tokenHelpId = useId();-return (<>- <FieldWithHelp>- <Form.Field- control={form.control}- name="githubDispatch.url"- label="Repository dispatch URL"- >- {(field) => (- <PrefixedInput- id={field.id}- name={field.name}- value={field.value}- onChange={(event) =>- field.onChange(stripUrlScheme(event.target.value))- }- onBlur={field.onBlur}- ref={field.ref}- prefix="https://"- inputMode="url"- placeholder="api.github.com/repos/owner/repo/dispatches"- aria-describedby={describedBy(- field.inputDescribedById,- urlHelpId,- )}- aria-invalid={!!field.error}- error={!!field.error}- />- )}- </Form.Field>- <FieldHelp id={urlHelpId}>- GitHub API endpoint for repository dispatch.{" "}- <HelpLink href={dispatchDocsUrl} text="Learn more" />- </FieldHelp>- </FieldWithHelp>- <FieldWithHelp>- <Form.Field- control={form.control}- name="githubDispatch.eventType"- label="Event type"- >- {(field) => (- <Input- id={field.id}- name={field.name}- value={field.value}- onChange={field.onChange}- onBlur={field.onBlur}- ref={field.ref}- placeholder="e.g. langfuse-alert"- aria-describedby={describedBy(- field.inputDescribedById,- eventTypeHelpId,- )}- aria-invalid={!!field.error}- error={!!field.error}- />- )}- </Form.Field>- <FieldHelp id={eventTypeHelpId}>- Add this to the <InlineCode>on.repository_dispatch.types</InlineCode>{" "}- filter in your workflow.- </FieldHelp>- </FieldWithHelp>- <FieldWithHelp>- <Form.Field- control={form.control}- name="githubDispatch.githubToken"- label="GitHub personal access token"- >- {(field) => (- <PasswordInput- id={field.id}- name={field.name}- value={field.value}- onChange={field.onChange}- onBlur={field.onBlur}- ref={field.ref}- placeholder="ghp_..."- aria-describedby={describedBy(- field.inputDescribedById,- tokenHelpId,- )}- aria-invalid={!!field.error}- error={!!field.error}- />- )}- </Form.Field>- <FieldHelp id={tokenHelpId}>- GitHub PAT with <InlineCode>repo</InlineCode> scope for repository- dispatch. <HelpLink href={createTokenUrl} text="Create token" />- </FieldHelp>- </FieldWithHelp>+ <Form.InputField+ control={form.control}+ name="githubDispatch.url"+ label="Repository dispatch URL"+ transformValue={stripUrlScheme}+ valuePrefix="https://"+ inputMode="url"+ placeholder="api.github.com/repos/owner/repo/dispatches"+ description={[+ {+ type: "text",+ text: "GitHub API endpoint for repository dispatch. ",+ },+ { type: "link", text: "Learn more", href: dispatchDocsUrl },+ ]}+ />+ <Form.InputField+ control={form.control}+ name="githubDispatch.eventType"+ label="Event type"+ placeholder="e.g. langfuse-alert"+ description={[+ { type: "text", text: "Add this to the " },+ { type: "code", text: "on.repository_dispatch.types" },+ { type: "text", text: " filter in your workflow." },+ ]}+ />+ <Form.PasswordInputField+ control={form.control}+ name="githubDispatch.githubToken"+ label="GitHub personal access token"+ placeholder="ghp_..."+ description={[+ { type: "text", text: "GitHub PAT with " },+ { type: "code", text: "repo" },+ { type: "text", text: " scope for repository dispatch. " },+ { type: "link", text: "Create token", href: createTokenUrl },+ ]}+ /></>);}diff --git a/web/src/features/monitors/automations/components/HelpLink.tsx b/web/src/features/monitors/automations/components/HelpLink.tsxdeleted file mode 100644index aa3b22340f..0000000000--- a/web/src/features/monitors/automations/components/HelpLink.tsx+++ /dev/null@@ -1,21 +0,0 @@-import { SquareArrowOutUpRight } from "@langfuse/icons";--/** HelpLink renders an underlined external link that sits inside field help text and opens in a new tab. */-export function HelpLink({ href, text }: { href: string; text: string }) {- return (- <a- className="text-link hover:text-link-hover underline underline-offset-2"- href={href}- target="_blank"- rel="noopener noreferrer"- >- {text}- <SquareArrowOutUpRight- aria-hidden- size="sm"- color="muted"- __rawClassName="ml-0.75 inline-block align-[-1px]"- />- </a>- );-}diff --git a/web/src/features/monitors/automations/components/InlineCode.tsx b/web/src/features/monitors/automations/components/InlineCode.tsxdeleted file mode 100644index e6920b848f..0000000000--- a/web/src/features/monitors/automations/components/InlineCode.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { type ReactNode } from "react";--import { cn } from "@/src/utils/tailwind";--/** InlineCode renders a code fragment inside help text. */-export function InlineCode({- children,- isShaded = false,-}: {- children: ReactNode;- isShaded?: boolean;-}) {- return (- <code- className={cn(- "font-mono text-xs",- isShaded && "bg-muted rounded-md px-1 py-px",- )}- >- {children}- </code>- );-}diff --git a/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.tsx b/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.tsxindex 1285b2c03e..94ae632a3a 100644--- a/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.tsx+++ b/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.tsx@@ -6,9 +6,7 @@ import { type ActionTypes } from "@langfuse/shared";import { type PagerDutyTestEventState } from "@/src/features/pagerduty";import { Dialog } from "@/src/components/design-system/Dialog/Dialog";import { Form } from "@/src/components/design-system/Form/Form";-import { Input } from "@/src/components/design-system/Input/Input";import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";-import { DividedDialogBody } from "./DividedDialogBody";import { GitHubDispatchActionFields } from "./GitHubDispatchActionFields";import { PagerDutyActionFields } from "./PagerDutyActionFields";import { SlackActionFields, type SlackFieldsState } from "./SlackActionFields";@@ -82,7 +80,7 @@ export function NewMonitorAutomationDialog({},]}>- <DividedDialogBody>+ <Dialog.Body separators="both"><Formid={formId}actions={[]}@@ -104,7 +102,7 @@ export function NewMonitorAutomationDialog({/>{rootError && <FormError message={rootError} />}</Form>- </DividedDialogBody>+ </Dialog.Body></Dialog>);}@@ -121,27 +119,13 @@ function FormError({ message }: { message: string }) {/** NameField is the automation name, shown on every alert it connects to. */function NameField({ form }: { form: MonitorAutomationForm }) {return (- <Form.Field+ <Form.InputFieldcontrol={form.control}name="name"label="Name"description="Can be connected to any alert in the project."- >- {(field) => (- <Input- id={field.id}- name={field.name}- value={field.value}- onChange={field.onChange}- onBlur={field.onBlur}- ref={field.ref}- placeholder="e.g. Staging alerts"- aria-describedby={field.inputDescribedById}- aria-invalid={!!field.error}- error={!!field.error}- />- )}- </Form.Field>+ placeholder="e.g. Staging alerts"+ />);}diff --git a/web/src/features/monitors/automations/components/PagerDutyActionFields.tsx b/web/src/features/monitors/automations/components/PagerDutyActionFields.tsxindex 909350a376..6cc940dd51 100644--- a/web/src/features/monitors/automations/components/PagerDutyActionFields.tsx+++ b/web/src/features/monitors/automations/components/PagerDutyActionFields.tsx@@ -1,4 +1,3 @@-import { useId } from "react";import { type UseFormReturn } from "react-hook-form";import { type PagerDutyRegion } from "@langfuse/shared/pagerduty";@@ -7,13 +6,7 @@ import {type PagerDutyTestEventState,} from "@/src/features/pagerduty";import { Form } from "@/src/components/design-system/Form/Form";-import { PasswordInput } from "@/src/components/design-system/PasswordInput/PasswordInput";-import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";import { type MonitorAutomationFormValues } from "../helpers/monitorAutomationFormSchema";-import { describedBy } from "../helpers/describedBy";-import { FieldHelp } from "./FieldHelp";-import { FieldWithHelp } from "./FieldWithHelp";-import { HelpLink } from "./HelpLink";const integrationDocsUrl ="https://support.pagerduty.com/main/docs/services-and-integrations#create-a-generic-events-api-integration";@@ -31,58 +24,32 @@ export function PagerDutyActionFields({form: UseFormReturn<MonitorAutomationFormValues>;testEvent: PagerDutyTestEventState;}) {- const routingKeyHelpId = useId();const routingKey = form.watch("pagerDuty.routingKey");const region = form.watch("pagerDuty.region");return (<>- <FieldWithHelp>- <Form.Field- control={form.control}- name="pagerDuty.routingKey"- label="Integration Key"- >- {(field) => (- <PasswordInput- id={field.id}- name={field.name}- value={field.value}- onChange={field.onChange}- onBlur={field.onBlur}- ref={field.ref}- placeholder="e.g. R0212P1QXGEIQE2NMTQ7L7WXD00DWHIN"- aria-describedby={describedBy(- field.inputDescribedById,- routingKeyHelpId,- )}- aria-invalid={!!field.error}- error={!!field.error}- />- )}- </Form.Field>- <FieldHelp id={routingKeyHelpId}>- Integration key for a PagerDuty Service or Event Orchestration.{" "}- <HelpLink href={integrationDocsUrl} text="Learn more" />- </FieldHelp>- </FieldWithHelp>- <Form.Field+ <Form.PasswordInputField+ control={form.control}+ name="pagerDuty.routingKey"+ label="Integration Key"+ placeholder="e.g. R0212P1QXGEIQE2NMTQ7L7WXD00DWHIN"+ description={[+ {+ type: "text",+ text: "Integration key for a PagerDuty Service or Event Orchestration. ",+ },+ { type: "link", text: "Learn more", href: integrationDocsUrl },+ ]}+ />+ <Form.SelectInputFieldcontrol={form.control}name="pagerDuty.region"label="Region"description="The service region of your PagerDuty account."- >- {(field) => (- <SelectInput<PagerDutyRegion>- id={field.id}- value={field.value}- onValueChange={field.onChange}- options={regionOptions}- placeholder="Select a region"- aria-describedby={field.inputDescribedById}- />- )}- </Form.Field>+ options={regionOptions}+ placeholder="Select a region"+ /><div className="flex"><PagerDutyTestEventButtonsViewtarget={{ region, routingKey: routingKey.trim() || undefined }}diff --git a/web/src/features/monitors/automations/components/PrefixedInput.stories.tsx b/web/src/features/monitors/automations/components/PrefixedInput.stories.tsxdeleted file mode 100644index 5d1b8d9694..0000000000--- a/web/src/features/monitors/automations/components/PrefixedInput.stories.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { expect, userEvent, within } from "storybook/test";--import preview from "@/.storybook/preview";-import { PrefixedInput } from "./PrefixedInput";--const meta = preview.meta({- component: PrefixedInput,- args: {- "aria-label": "Webhook URL",- addon: "POST",- prefix: "https://",- placeholder: "example.com/webhook",- },-});--export const Default = meta.story({});--export const WithoutAddon = meta.story({- args: {- "aria-label": "Repository dispatch URL",- addon: undefined,- placeholder: "api.github.com/repos/owner/repo/dispatches",- },-});--export const Invalid = meta.story({- args: { value: "not a url", error: true, "aria-invalid": true },-});--export const TestFocusesOnAddonClick = meta.story({- name: "(Test) Focuses on addon click",- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await userEvent.click(canvas.getByText("POST"));- await expect(- canvas.getByRole("textbox", { name: "Webhook URL" }),- ).toHaveFocus();- },-});diff --git a/web/src/features/monitors/automations/components/PrefixedInput.tsx b/web/src/features/monitors/automations/components/PrefixedInput.tsxdeleted file mode 100644index 866f780efe..0000000000--- a/web/src/features/monitors/automations/components/PrefixedInput.tsx+++ /dev/null@@ -1,90 +0,0 @@-import {- useRef,- type InputHTMLAttributes,- type MouseEvent,- type Ref,- type RefObject,-} from "react";--import { cn } from "@/src/utils/tailwind";--/** PrefixedInput renders a text input after an optional shaded addon and a muted prefix inside one shared border. */-export function PrefixedInput({- addon,- prefix,- error,- ref,- ...props-}: Pick<- InputHTMLAttributes<HTMLInputElement>,- | "aria-describedby"- | "aria-invalid"- | "id"- | "inputMode"- | "name"- | "onBlur"- | "onChange"- | "placeholder"- | "value"-> & {- addon?: string;- prefix: string;- error?: boolean;- ref?: Ref<HTMLInputElement>;-}) {- const inputRef = useRef<HTMLInputElement | null>(null);-- return (- <div- className={cn(- "bg-background ring-offset-background focus-within:ring-ring flex h-8 w-full min-w-0 cursor-text items-center overflow-hidden rounded-md border text-sm focus-within:ring-2 focus-within:ring-offset-2",- borderClassName(error),- )}- onMouseDown={(event) => focusInput(event, inputRef)}- >- {addon && (- <span className="bg-muted text-muted-foreground border-input flex h-full shrink-0 items-center border-r px-2.5 font-mono text-xs">- {addon}- </span>- )}- <span className="text-foreground-secondary shrink-0 pr-0.5 pl-3">- {prefix}- </span>- <input- {...props}- className="placeholder:text-muted-foreground h-full min-w-0 flex-1 border-0 bg-transparent py-0 pr-3 pl-0 text-sm shadow-none outline-hidden focus:ring-0"- data-1p-ignore- ref={(input) => attachInput(input, inputRef, ref)}- />- </div>- );-}--/** borderClassName colors the shared border and focus ring for the error state. */-function borderClassName(error: boolean | undefined): string {- if (error) {- return "border-destructive focus-within:ring-destructive/40 focus-within:ring-offset-0";- }- return "border-input";-}--/** focusInput moves focus to the input when the addon or prefix is pressed. */-function focusInput(- event: MouseEvent<HTMLDivElement>,- inputRef: RefObject<HTMLInputElement | null>,-) {- if (event.target === inputRef.current) return;- event.preventDefault();- inputRef.current?.focus();-}--/** attachInput stores the input locally and forwards it to the caller's ref. */-function attachInput(- input: HTMLInputElement | null,- inputRef: RefObject<HTMLInputElement | null>,- ref: Ref<HTMLInputElement> | undefined,-) {- inputRef.current = input;- if (typeof ref === "function") ref(input);- else if (ref) ref.current = input;-}diff --git a/web/src/features/monitors/automations/components/SlackActionFields.tsx b/web/src/features/monitors/automations/components/SlackActionFields.tsxindex ba5314ae3f..ff817c7a08 100644--- a/web/src/features/monitors/automations/components/SlackActionFields.tsx+++ b/web/src/features/monitors/automations/components/SlackActionFields.tsx@@ -1,4 +1,4 @@-import { useId, useState } from "react";+import { useState } from "react";import { type UseFormReturn } from "react-hook-form";import { SiSlack } from "@langfuse/icons/si";@@ -12,9 +12,6 @@ import {} from "@/src/features/slack";import { type MonitorAutomationFormValues } from "../helpers/monitorAutomationFormSchema";import { FieldGroup } from "./FieldGroup";-import { InlineCode } from "./InlineCode";-import { FieldHelp } from "./FieldHelp";-import { FieldWithHelp } from "./FieldWithHelp";/** SlackActionFields picks the channel of a connected workspace, or offers to connect one. */export function SlackActionFields({@@ -74,7 +71,6 @@ function SlackChannelFields({const channelId = form.watch("slack.channelId");const channelName = form.watch("slack.channelName");const selectedChannel = selectedSlackChannel(channelId, channelName);- const channelHelpId = useId();const [testResult, setTestResult] = useState<SlackTestMessageResult>();const selectChannel = (channel: SlackChannel) => {form.setValue("slack.channelId", channel.id);@@ -83,32 +79,35 @@ function SlackChannelFields({return (<>- <FieldWithHelp>- <Form.Field- control={form.control}- name="slack.channelId"- label="Slack channel"- >- {() => (- <ChannelSelectorView- {...channelSelectorData(slack)}- selectedChannelId={channelId}- selectedChannel={selectedChannel}- onChannelSelect={(channel) => {- setTestResult(undefined);- selectChannel(channel);- }}- placeholder="Select a channel"- />- )}- </Form.Field>- <FieldHelp id={channelHelpId}>- Select the Slack channel where notifications will be sent. Private- channels appear only for the person who connected Slack, and only if- both they and the app are members. Invite the app with{" "}- <InlineCode isShaded>/invite @Langfuse</InlineCode>.- </FieldHelp>- </FieldWithHelp>+ <Form.Field+ control={form.control}+ name="slack.channelId"+ label="Slack channel"+ description={[+ {+ type: "text",+ text: "Select the Slack channel where notifications will be sent. Private channels appear only for the person who connected Slack, and only if both they and the app are members. Invite the app with ",+ },+ { type: "code", text: "/invite @Langfuse" },+ { type: "text", text: "." },+ ]}+ >+ {(field) => (+ <ChannelSelectorView+ {...channelSelectorData(slack)}+ id={field.id}+ aria-describedby={field.inputDescribedById}+ aria-invalid={!!field.error}+ selectedChannelId={channelId}+ selectedChannel={selectedChannel}+ onChannelSelect={(channel) => {+ setTestResult(undefined);+ selectChannel(channel);+ }}+ placeholder="Select a channel"+ />+ )}+ </Form.Field>{selectedChannel && slack.status === "connected" && (<div className="flex items-center gap-3"><Buttondiff --git a/web/src/features/monitors/automations/components/WebhookActionFields.tsx b/web/src/features/monitors/automations/components/WebhookActionFields.tsxindex 9ee2de4864..98370fe479 100644--- a/web/src/features/monitors/automations/components/WebhookActionFields.tsx+++ b/web/src/features/monitors/automations/components/WebhookActionFields.tsx@@ -14,7 +14,6 @@ import { Input } from "@/src/components/design-system/Input/Input";import { type MonitorAutomationFormValues } from "../helpers/monitorAutomationFormSchema";import { stripUrlScheme } from "../helpers/stripUrlScheme";import { FieldGroup } from "./FieldGroup";-import { PrefixedInput } from "./PrefixedInput";const defaultHeaders = [{@@ -49,32 +48,17 @@ function WebhookUrlField({form: UseFormReturn<MonitorAutomationFormValues>;}) {return (- <Form.Field+ <Form.InputFieldcontrol={form.control}name="webhook.url"label="Webhook URL"description="Called whenever the severity changes."- >- {(field) => (- <PrefixedInput- id={field.id}- name={field.name}- value={field.value}- onChange={(event) =>- field.onChange(stripUrlScheme(event.target.value))- }- onBlur={field.onBlur}- ref={field.ref}- addon="POST"- prefix="https://"- inputMode="url"- placeholder="example.com/webhook"- aria-describedby={field.inputDescribedById}- aria-invalid={!!field.error}- error={!!field.error}- />- )}- </Form.Field>+ transformValue={stripUrlScheme}+ prefix={{ label: "POST" }}+ valuePrefix="https://"+ inputMode="url"+ placeholder="example.com/webhook"+ />);}diff --git a/web/src/features/monitors/automations/components/WebhookSecretDialog.tsx b/web/src/features/monitors/automations/components/WebhookSecretDialog.tsxindex e7e89727e7..526cca8924 100644--- a/web/src/features/monitors/automations/components/WebhookSecretDialog.tsx+++ b/web/src/features/monitors/automations/components/WebhookSecretDialog.tsx@@ -1,4 +1,4 @@-import { useId, useState } from "react";+import { useState } from "react";import { Check, Copy } from "@langfuse/icons";import { Dialog } from "@/src/components/design-system/Dialog/Dialog";@@ -6,11 +6,6 @@ import { Form } from "@/src/components/design-system/Form/Form";import { IconButton } from "@/src/components/design-system/IconButton/IconButton";import { Input } from "@/src/components/design-system/Input/Input";import { copyTextToClipboard } from "@/src/utils/clipboard";-import { DividedDialogBody } from "./DividedDialogBody";-import { InlineCode } from "./InlineCode";-import { describedBy } from "../helpers/describedBy";-import { FieldHelp } from "./FieldHelp";-import { FieldWithHelp } from "./FieldWithHelp";/** WebhookSecretDialog shows a just-created webhook automation's signing secret, which is never shown again. */export function WebhookSecretDialog({@@ -20,7 +15,6 @@ export function WebhookSecretDialog({automationName: string;webhookSecret: string;}) {- const secretHelpId = useId();const [copyStatus, setCopyStatus] = useState<CopyStatus>("idle");return (@@ -28,47 +22,46 @@ export function WebhookSecretDialog({title={`Automation "${automationName}" was created`}closeLabel="Done">- <DividedDialogBody>- <FieldWithHelp>- <Form.Field label="Webhook secret">- {(field) => (- <div className="flex flex-col gap-1">- <div className="ph-no-capture grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2">- <Input- id={field.id}- value={webhookSecret}- aria-describedby={describedBy(- field.inputDescribedById,- secretHelpId,- )}- readOnly- />- <IconButton- icon={copyIcon(copyStatus)}- label={copyLabel(copyStatus)}- variant="outline"- onClick={async () =>- setCopyStatus(await copySecret(webhookSecret))- }- />- </div>- {copyStatus === "failed" && (- <p role="alert" className="text-destructive text-sm">- Copy failed. Select the secret and copy it manually.- </p>- )}+ <Dialog.Body separators="both">+ <Form.Field+ label="Webhook secret"+ description={[+ {+ type: "text",+ text: "Use this secret to verify webhook signatures. It is included in the ",+ },+ { type: "code", text: "x-langfuse-signature" },+ { type: "text", text: " header. " },+ { type: "strong", text: "This will not be shown again." },+ ]}+ >+ {(field) => (+ <div className="flex flex-col gap-1">+ <div className="ph-no-capture grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2">+ <Input+ id={field.id}+ value={webhookSecret}+ aria-describedby={field.inputDescribedById}+ readOnly+ />+ <IconButton+ icon={copyIcon(copyStatus)}+ label={copyLabel(copyStatus)}+ variant="outline"+ onClick={async () =>+ setCopyStatus(await copySecret(webhookSecret))+ }+ /></div>- )}- </Form.Field>- <FieldHelp id={secretHelpId}>- Use this secret to verify webhook signatures. It is included in the{" "}- <InlineCode isShaded>x-langfuse-signature</InlineCode> header.{" "}- <strong className="text-foreground font-bold">- This will not be shown again.- </strong>- </FieldHelp>- </FieldWithHelp>- </DividedDialogBody>+ {copyStatus === "failed" && (+ <p role="alert" className="text-destructive text-sm">+ Copy failed. Select the secret and copy it manually.+ </p>+ )}+ </div>+ )}+ </Form.Field>+ </Dialog.Body></Dialog>);}diff --git a/web/src/features/monitors/automations/helpers/describedBy.ts b/web/src/features/monitors/automations/helpers/describedBy.tsdeleted file mode 100644index ec8c7399db..0000000000--- a/web/src/features/monitors/automations/helpers/describedBy.ts+++ /dev/null@@ -1,8 +0,0 @@-/** describedBy joins the ids an input's aria-describedby should list, skipping missing ones. */-export function describedBy(- ...ids: (string | undefined)[]-): string | undefined {- const present = ids.filter((id) => id !== undefined);- if (present.length === 0) return undefined;- return present.join(" ");-}diff --git a/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.tsx b/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.tsxindex 6c34400295..5b69b83470 100644--- a/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.tsx+++ b/web/src/features/slack/components/ChannelSelectorView/ChannelSelectorView.tsx@@ -1,27 +1,14 @@-/* eslint-disable @typescript-eslint/no-use-before-define */-import React, { useState, useMemo, useCallback, useEffect } from "react";-import { RefreshCw, Search, Hash, Lock, AlertTriangle } from "@langfuse/icons";-import { Button } from "@/src/components/ui/button";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/src/components/ui/popover";+import React, { useState, useMemo } from "react";+import { RefreshCw, Hash, Lock, AlertTriangle } from "@langfuse/icons";+import { AsyncSelectInput } from "@/src/components/design-system/AsyncSelectInput/AsyncSelectInput";import { Alert } from "@/src/components/design-system/Alert/Alert";import { IconButton } from "@/src/components/design-system/IconButton/IconButton";-import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,-} from "@/src/components/ui/command";-import { useVirtualizer } from "@tanstack/react-virtual";import { type SlackChannel } from "@langfuse/shared/src/server";-const ITEM_HEIGHT = 32;export interface ChannelSelectorViewProps {+ id?: string;+ "aria-describedby"?: string;+ "aria-invalid"?: React.AriaAttributes["aria-invalid"];/** Loaded channels and private channel flags; null until the first page loads */channelsData: {channels: SlackChannel[];@@ -58,6 +45,9 @@ export interface ChannelSelectorViewProps {* Items are virtualized with @tanstack/react-virtual to handle large channel lists (~5k).*/export const ChannelSelectorView: React.FC<ChannelSelectorViewProps> = ({+ id,+ "aria-describedby": describedBy,+ "aria-invalid": invalid,channelsData,isLoading,hasError,@@ -73,9 +63,7 @@ export const ChannelSelectorView: React.FC<ChannelSelectorViewProps> = ({filterChannels,showRefreshButton = true,}) => {- const [open, setOpen] = useState(false);const [searchValue, setSearchValue] = useState("");- const [scrollNode, setScrollNode] = useState<HTMLDivElement | null>(null);const trimmedSearch = searchValue.trim();const effectiveName = trimmedSearch.replace(/^#/, "");@@ -112,13 +100,6 @@ export const ChannelSelectorView: React.FC<ChannelSelectorViewProps> = ({});}, [channelsData?.channels, memberOnly, filterChannels, effectiveName]);- const virtualizer = useVirtualizer({- count: filteredChannels.length,- getScrollElement: () => scrollNode,- estimateSize: () => ITEM_HEIGHT,- overscan: 20,- });-// Get selected channel info — fall back to the prop for manual entriesconst selectedChannel = useMemo(() => {if (!selectedChannelId) return null;@@ -128,39 +109,6 @@ export const ChannelSelectorView: React.FC<ChannelSelectorViewProps> = ({return fromList ?? selectedChannelProp ?? null;}, [selectedChannelId, channelsData?.channels, selectedChannelProp]);- const selectAndClose = useCallback(- (channel: SlackChannel) => {- onChannelSelect(channel);- setOpen(false);- setSearchValue("");- },- [onChannelSelect],- );-- const handleSelectByName = useCallback(() => {- const name = searchValue.trim().replace(/^#/, "");- if (!name) return;- selectAndClose({- id: `#${name}`,- name,- isPrivate: false,- isMember: false,- });- }, [searchValue, selectAndClose]);-- const handleOpenChange = (newOpen: boolean) => {- setOpen(newOpen);- if (!newOpen) {- setSearchValue("");- }- };-- useEffect(() => {- if (scrollNode) {- scrollNode.scrollTop = 0;- }- }, [effectiveName, scrollNode]);-const hasExactMatch = filteredChannels.some((channel) => channel.name.toLowerCase() === effectiveName.toLowerCase(),);@@ -169,107 +117,66 @@ export const ChannelSelectorView: React.FC<ChannelSelectorViewProps> = ({return (<div className="space-y-2"><div className="flex items-center gap-2">- <Popover open={open} onOpenChange={handleOpenChange}>- <PopoverTrigger asChild>- <Button- variant="outline"- role="combobox"- aria-expanded={open}- className="w-full justify-between"- disabled={disabled}- >- {selectedChannel ? (- <ChannelLabel channel={selectedChannel} />- ) : (- <span className="text-muted-foreground">{placeholder}</span>- )}- <Search- size="base"- color="default"- __rawClassName="ml-2 opacity-50"- />- </Button>- </PopoverTrigger>- <PopoverContent className="w-full p-0" align="start">- <Command shouldFilter={false}>- <CommandInput- placeholder="Search channels..."- value={searchValue}- onValueChange={setSearchValue}- />- <CommandList ref={setScrollNode}>- {canUseTypedName && (- <CommandGroup className="p-0">- <CommandItem- value={`use-${effectiveName}`}- onSelect={handleSelectByName}- className="cursor-pointer"- >- <Hash size="base" color="muted" />- <span- className="flex-1 truncate"- title={`Use " ${effectiveName} "`}- >- Use "{effectiveName}"- </span>- </CommandItem>- </CommandGroup>- )}- {!isLoading &&- !canUseTypedName &&- filteredChannels.length === 0 && (- <CommandEmpty>No channels available.</CommandEmpty>- )}- <CommandGroup- className="p-0"- style={{- height: virtualizer.getTotalSize(),- position: "relative",- }}- >- {virtualizer.getVirtualItems().map((virtualRow) => {- const channel = filteredChannels[virtualRow.index];- return (- <CommandItem- key={channel.id}- value={channel.id}- onSelect={() => selectAndClose(channel)}- className="cursor-pointer"- style={{- position: "absolute",- top: virtualRow.start,- left: 0,- width: "100%",- height: ITEM_HEIGHT,- }}- >- <ChannelLabel channel={channel} />- </CommandItem>- );- })}- </CommandGroup>- {isLoading && (- <CommandGroup className="p-0">- <CommandItem- value="loading-slack-channels"- disabled- className="text-muted-foreground"- >- <RefreshCw size="base" __rawClassName="animate-spin" />- <span- className="flex-1 truncate"- title="Loading Slack channels. This can take a while for large workspaces."- >- Loading Slack channels. This can take a while for large- workspaces.- </span>- </CommandItem>- </CommandGroup>- )}- </CommandList>- </Command>- </PopoverContent>- </Popover>+ <div className="min-w-0 flex-1">+ <AsyncSelectInput+ id={id}+ aria-describedby={describedBy}+ aria-invalid={invalid}+ disabled={disabled}+ error={invalid === true || invalid === "true"}+ placeholder={placeholder}+ value={+ selectedChannel+ ? {+ value: selectedChannel.id,+ label: selectedChannel.name,+ icon: selectedChannel.isPrivate ? Lock : Hash,+ }+ : null+ }+ callToActionOption={+ canUseTypedName+ ? {+ position: "first",+ label: `Use "${effectiveName}"`,+ onSelect: () =>+ onChannelSelect({+ id: `#${effectiveName}`,+ name: effectiveName,+ isPrivate: false,+ isMember: false,+ }),+ }+ : undefined+ }+ options={filteredChannels.map((channel) => ({+ value: channel.id,+ label: channel.name,+ icon: channel.isPrivate ? Lock : Hash,+ }))}+ onValueChange={(option) => {+ const channel = filteredChannels.find(+ (item) => item.id === option.value,+ );+ if (channel) onChannelSelect(channel);+ }}+ search={{+ placeholder: "Search channels...",+ value: searchValue,+ onValueChange: setSearchValue,+ }}+ emptyMessage="No channels available."+ loading={+ isLoading+ ? {+ message:+ "Loading Slack channels. This can take a while for large workspaces.",+ }+ : undefined+ }+ virtualized+ />+ </div>{showRefreshButton && (<IconButton@@ -317,16 +224,3 @@ export const ChannelSelectorView: React.FC<ChannelSelectorViewProps> = ({</div>);};--const ChannelLabel = ({ channel }: { channel: SlackChannel }) => (- <div className="flex w-full items-center gap-2">- {channel.isPrivate ? (- <Lock size="base" color="muted" />- ) : (- <Hash size="base" color="muted" />- )}- <span className="flex-1 truncate" title={channel.name}>- {channel.name}- </span>- </div>-);