` element.
**Props**
| Prop | Type | Default | Description |
| ---------------- | --------------------- | ------- | ------------------------------------------------- |
| `children` | `React.ReactNode` | — | The dialog content, rendered inside the popup. |
| `backdropProps?` | `DialogBackdropProps` | — | Props for the backdrop rendered behind the popup. |
Inherits `className`, `render`, `style`, `initialFocus`, `finalFocus` from [Base UI Dialog.Popup](https://base-ui.com/react/components/dialog#popup).
**Data attributes**
| Attribute | Description |
| ------------------------- | ---------------------------------------------------------------- |
| `data-open` | Present when the dialog is open. |
| `data-closed` | Present when the dialog is closed. |
| `data-starting-style` | Present when the dialog begins animating in. |
| `data-ending-style` | Present when the dialog is animating out. |
| `data-nested` | Present when the dialog is nested within another dialog. |
| `data-nested-dialog-open` | Present when the dialog has other open dialogs nested within it. |
**CSS variables**
| Variable | Type | Description |
| ------------------ | -------- | --------------------------------------------- |
| `--nested-dialogs` | `number` | Indicates how many dialogs are nested within. |
### DialogDescription
A paragraph with additional information about the dialog. Renders a `
` element.
Inherits `className`, `render`, `style` from [Base UI Dialog.Description](https://base-ui.com/react/components/dialog#description).
### DialogFooter
Accepts the props of the element it renders.
### DialogHeader
Accepts the props of the element it renders.
### DialogHeaderCloseButton
An icon close button positioned in the corner of `DialogHeader`, which reserves space for it automatically. Renders a `` element.
**Props**
| Prop | Type | Default | Description |
| ------------ | -------- | ------- | -------------------------------------------------------------------------------------------------------- |
| `aria-label` | `string` | — | Defines a string value that labels the current element. Names the close button for assistive technology. |
Inherits `style`, `nativeButton` from [Base UI Dialog.Close](https://base-ui.com/react/components/dialog#close).
**Data attributes**
| Attribute | Description |
| --------------- | ------------------------------------ |
| `data-disabled` | Present when the button is disabled. |
### DialogPopup
A container for the dialog contents. Renders a `` element.
Inherits `className`, `render`, `style`, `initialFocus`, `finalFocus` from [Base UI Dialog.Popup](https://base-ui.com/react/components/dialog#popup).
**Data attributes**
| Attribute | Description |
| ------------------------- | ---------------------------------------------------------------- |
| `data-open` | Present when the dialog is open. |
| `data-closed` | Present when the dialog is closed. |
| `data-starting-style` | Present when the dialog begins animating in. |
| `data-ending-style` | Present when the dialog is animating out. |
| `data-nested` | Present when the dialog is nested within another dialog. |
| `data-nested-dialog-open` | Present when the dialog has other open dialogs nested within it. |
**CSS variables**
| Variable | Type | Description |
| ------------------ | -------- | --------------------------------------------- |
| `--nested-dialogs` | `number` | Indicates how many dialogs are nested within. |
### DialogPortal
A portal element that moves the popup to a different part of the DOM. By default, the portal element is appended to ``. Renders a `
` element.
Inherits `keepMounted`, `container`, `className`, `render`, `style` from [Base UI Dialog.Portal](https://base-ui.com/react/components/dialog#portal).
### DialogTitle
A heading that labels the dialog. Renders an `
` element.
Inherits `className`, `render`, `style` from [Base UI Dialog.Title](https://base-ui.com/react/components/dialog#title).
### DialogTrigger
A button that opens the dialog. Renders a `` element.
Inherits `handle`, `payload`, `id`, `className`, `render`, `style`, `nativeButton` from [Base UI Dialog.Trigger](https://base-ui.com/react/components/dialog#trigger).
**Data attributes**
| Attribute | Description |
| ----------------- | ---------------------------------------------- |
| `data-disabled` | Present when the trigger is disabled. |
| `data-popup-open` | Present when the corresponding dialog is open. |
### DialogViewport
A positioning container for the dialog popup that can be made scrollable. Renders a `` element.
Inherits `className`, `render`, `style` from [Base UI Dialog.Viewport](https://base-ui.com/react/components/dialog#viewport).
**Data attributes**
| Attribute | Description |
| ------------------------- | ---------------------------------------------------------------- |
| `data-open` | Present when the dialog is open. |
| `data-closed` | Present when the dialog is closed. |
| `data-starting-style` | Present when the dialog begins animating in. |
| `data-ending-style` | Present when the dialog is animating out. |
| `data-nested` | Present when the dialog is nested within another dialog. |
| `data-nested-dialog-open` | Present when the dialog has other open dialogs nested within it. |
### createDialogHandle
Creates a new handle to connect a Dialog.Root with detached Dialog.Trigger components.
```ts
createDialogHandle
(): BaseDialog.Handle
```
**Returns:** `BaseDialog.Handle`
**Return properties**
| Member | Type | Description |
| ----------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open` | `(triggerId: string \| null) => void` | Opens the dialog, optionally associating it with a trigger. This method should only be called in an event handler or an effect (not during rendering). |
| `openWithPayload` | `(payload: Payload) => void` | Opens the dialog with the given payload, without associating it with any trigger. This method should only be called in an event handler or an effect (not during rendering). |
| `close` | `() => void` | Closes the dialog. This method should only be called in an event handler or an effect (not during rendering). |
| `isOpen` | `boolean` | Whether the dialog is currently open. Returns `false` while no root is attached to the handle. |
# Direction Provider
> A context that switches components to right-to-left behavior.
```tsx title="hero.tsx"
import type { TextDirection } from '@langgenius/dify-ui/direction-provider'
import { DirectionProvider } from '@langgenius/dify-ui/direction-provider'
import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
import {
Slider,
SliderControl,
SliderIndicator,
SliderLabel,
SliderThumb,
SliderTrack,
SliderValue,
} from '@langgenius/dify-ui/slider'
import { Tabs, TabsIndicator, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'
import * as React from 'react'
const copy = {
ltr: {
lang: 'en',
tabsLabel: 'Model settings',
tabs: [
{
value: 'prompt',
label: 'Prompt',
panel: 'Instructions the model follows in every conversation.',
},
{
value: 'parameters',
label: 'Parameters',
panel: 'Temperature, top P and the maximum number of tokens.',
},
{ value: 'debug', label: 'Debug', panel: 'Send test messages and inspect each run.' },
],
temperature: 'Temperature',
},
rtl: {
lang: 'ar',
tabsLabel: 'إعدادات النموذج',
tabs: [
{ value: 'prompt', label: 'الموجّه', panel: 'التعليمات التي يتبعها النموذج في كل محادثة.' },
{
value: 'parameters',
label: 'المعلمات',
panel: 'درجة الحرارة وقيمة Top P والحد الأقصى للرموز.',
},
{ value: 'debug', label: 'تصحيح الأخطاء', panel: 'أرسل رسائل تجريبية وافحص كل تشغيل.' },
],
temperature: 'درجة الحرارة',
},
} as const
export function DirectionProviderHeroDemo() {
const [direction, setDirection] = React.useState('rtl')
const text = copy[direction]
return (
Left to right
Right to left
{text.tabs.map((tab) => (
{tab.label}
))}
{text.tabs.map((tab) => (
{tab.panel}
))}
{text.temperature}
)
}
```
## Usage guidelines
- **Set `dir` as well**: `DirectionProvider` tells components which way the inline axis runs, so arrow keys, slider values and popup placement follow it. In the example above, right to left makes `ArrowLeft` move to the next tab and raise the slider value. The provider renders no element and does not change CSS. Set the HTML `dir` attribute on the same subtree, usually on ``, so layout, logical utilities and `:dir()` selectors follow.
- **Wrap the app once**: Put one provider near the root with the locale's direction. Nest another only for a region written in a different direction from the page.
- **Pass `dir` to popups in a nested region**: Popups render in a portal under ``, outside the region's `dir`. Read the direction with `useDirection` from a component inside the provider and pass it as `dir` to the content part of every popup in the region, including submenus and popups opened from another popup. A page that sets `dir` on `` needs no extra step.
- **Write direction-neutral styles**: Use logical utilities such as `ps-*`, `me-*`, `start-*` and `text-start` for spacing, offsets, borders and alignment, so one class list serves both directions. Caller overrides use the same family, because `cn` does not merge `pl-*` with `ps-*`.
- **Read the direction only when a value must leave CSS**: `useDirection` returns `'ltr'` or `'rtl'` for code that computes geometry or passes `dir` to portaled content. Prefer a `:dir(rtl)` or `rtl:` variant for anything CSS can express.
## Anatomy
```tsx
import { DirectionProvider, useDirection } from '@langgenius/dify-ui/direction-provider'
```
```tsx
```
## Examples
### Popups in a right-to-left region
Placement and keyboard read the provider, so the submenu opens toward the left and `ArrowLeft` opens it. Text, logical utilities and `:dir()` read the DOM instead, and a portaled popup inherits the direction and language of ``. Each menu here receives `dir` from `useDirection` and `lang="ar"`, so its items, submenu chevron and screen-reader language all match the region.
```tsx title="portaled-popup.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { DirectionProvider, useDirection } from '@langgenius/dify-ui/direction-provider'
import {
Menu,
MenuContent,
MenuItem,
MenuSeparator,
MenuSubmenu,
MenuSubmenuTrigger,
MenuTrigger,
} from '@langgenius/dify-ui/menu'
const folders = ['وثائق المنتج', 'تذاكر الدعم', 'ملاحظات الإصدار']
function DocumentMenu() {
const direction = useDirection()
return (
}
>
إجراءات المستند
إعادة التسمية
تنزيل
نقل إلى
{folders.map((folder) => (
{folder}
))}
حذف
)
}
export function DirectionProviderPortaledPopupDemo() {
return (
)
}
```
## API reference
### DirectionProvider
Enables RTL behavior for Dify UI and Base UI components. Doesn't render its own HTML element.
Inherits `children`, `direction` from [Base UI DirectionProvider](https://base-ui.com/react/utils/direction-provider).
### useDirection
```ts
useDirection(): 'ltr' | 'rtl'
```
**Returns:** `'ltr' | 'rtl'`
# Drawer
> A panel that slides in from a screen edge and dismisses with a swipe.
```tsx title="hero.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
Drawer,
DrawerBackdrop,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerPopup,
DrawerPortal,
DrawerTitle,
DrawerTrigger,
DrawerViewport,
} from '@langgenius/dify-ui/drawer'
import { IconButton } from '@langgenius/dify-ui/icon-button'
const details = [
{ label: 'App mode', value: 'Chatflow' },
{ label: 'Model', value: 'gpt-4o' },
{ label: 'Knowledge bases', value: 'Product docs, Refund policy' },
{ label: 'Service endpoint', value: '/v1/chat-messages', mono: true },
{ label: 'Rate limit', value: '60 requests / min', tabular: true },
{ label: 'Memory window', value: '12 messages', tabular: true },
]
export function DrawerHeroDemo() {
return (
}>App details
Customer support bot
Published configuration for the active production release.
}
/>
{details.map((item) => (
{item.label}
{item.value}
))}
}>Close
)
}
```
## Usage guidelines
- Use `Drawer` for a side panel or bottom sheet that follows the drawer model: it slides in from an edge and the user can swipe it away. A centered modal task uses `Dialog`.
- Set `swipeDirection` to the edge the drawer dismisses toward. It defaults to `down` for a bottom sheet; `right` and `left` make full-height side panels, and `DrawerPopup` styles each direction from `data-swipe-direction`.
- Compose `DrawerPortal`, `DrawerBackdrop`, `DrawerViewport` and `DrawerPopup` explicitly. Put the panel's content in `DrawerContent`, which scrolls and lets mouse users select text without starting a swipe.
- Every drawer has a `DrawerTitle`, which names it. Add a `DrawerDescription` when a sentence of context helps.
- `DrawerClose` is unstyled. Compose it with `IconButton` and an `aria-label` for the corner close icon of a side panel, or with `Button` for a footer action. A bottom sheet with a handle needs no visible close icon; keep a visually hidden `DrawerClose` so screen reader users, who cannot swipe, still have a way out.
- Use `DrawerTrigger` under the root for a dedicated button. Items of a list open one drawer at the list by passing `payload`; a trigger outside the root connects through `createDrawerHandle`, and controlled `open` is for open state another owner must observe.
- Set `modal={false}` for a panel the user works beside, such as a detail view next to the page. Pair it with `disablePointerDismissal` when clicks on the page should not close it.
## Anatomy
```tsx
import {
Drawer,
DrawerBackdrop,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerPopup,
DrawerPortal,
DrawerTitle,
DrawerTrigger,
DrawerViewport,
} from '@langgenius/dify-ui/drawer'
```
```tsx
```
`DrawerSwipeArea`, `DrawerProvider`, `DrawerIndent`, `DrawerIndentBackground` and `DrawerVirtualKeyboardProvider` add swipe-to-open, the indent effect and software keyboard handling from Base UI.
## Examples
### Bottom sheet
Without `swipeDirection`, the drawer is a bottom sheet that the user swipes down to dismiss. A decorative handle at the top hints at the gesture, so the visible close icon is dropped and a visually hidden `DrawerClose` remains for screen readers.
```tsx title="bottom-sheet.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
Drawer,
DrawerBackdrop,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerPopup,
DrawerPortal,
DrawerTitle,
DrawerTrigger,
DrawerViewport,
} from '@langgenius/dify-ui/drawer'
const channels = [
{ icon: 'i-ri-global-line', label: 'Public web app' },
{ icon: 'i-ri-code-s-slash-line', label: 'Embed on a website' },
{ icon: 'i-ri-terminal-box-line', label: 'Backend service API' },
]
export function DrawerBottomSheetDemo() {
return (
}>Publish app
Publish Customer support bot
Choose where people reach the published version.
Close
{channels.map((channel) => (
}>
{channel.label}
))}
)
}
```
### One drawer for a list of items
A list whose items open the same drawer renders one `Drawer` around the list. Each `DrawerTrigger` carries its item as `payload`, and the drawer reads the payload of the trigger that opened it.
```tsx title="payload.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
Drawer,
DrawerBackdrop,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerPopup,
DrawerPortal,
DrawerTitle,
DrawerTrigger,
DrawerViewport,
} from '@langgenius/dify-ui/drawer'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import * as React from 'react'
type Run = {
id: string
startedAt: string
status: 'Succeeded' | 'Failed'
duration: string
tokens: string
}
const runs: Run[] = [
{ id: '8f2c', startedAt: 'Today, 09:41', status: 'Succeeded', duration: '2.4s', tokens: '1,284' },
{ id: '7a19', startedAt: 'Today, 09:12', status: 'Failed', duration: '0.8s', tokens: '312' },
{
id: '6d03',
startedAt: 'Yesterday, 18:05',
status: 'Succeeded',
duration: '3.1s',
tokens: '2,047',
},
]
function RunStatus({ status }: { status: Run['status'] }) {
return (
{status}
)
}
export function DrawerPayloadDemo() {
return (
swipeDirection="right">
{({ payload }) => (
Run {payload?.id}
Started {payload?.startedAt}
}
/>
{payload && (
Status
Duration
{payload.duration}
Tokens
{payload.tokens}
)}
)}
)
}
```
### Non-modal panel
With `modal={false}` and `disablePointerDismissal`, the page behind stays interactive and clicks on it leave the panel open. Without a backdrop, the viewport passes pointer events through to the page.
```tsx title="non-modal.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerPopup,
DrawerPortal,
DrawerTitle,
DrawerTrigger,
DrawerViewport,
} from '@langgenius/dify-ui/drawer'
import { IconButton } from '@langgenius/dify-ui/icon-button'
const tools = [
{ name: 'search_web', description: 'Searches the web and returns the top results.' },
{ name: 'fetch_page', description: 'Reads the text content of a public URL.' },
{ name: 'summarize', description: 'Condenses a long passage into key points.' },
]
export function DrawerNonModalDemo() {
return (
}>Tool details
Web Research
3 tools available to agents in this workspace.
}
/>
{tools.map((tool) => (
{tool.name}
{tool.description}
))}
)
}
```
## Keyboard
| Key | Action |
| ---------------------- | ---------------------------------------------------------------------------------------------- |
| `Enter`, `Space` | Opens the drawer from a focused trigger. |
| `Tab`, `Shift` + `Tab` | Moves focus between the drawer's controls. Focus stays inside a modal drawer while it is open. |
| `Escape` | Closes the drawer and returns focus to the trigger. |
## API reference
### Drawer
Groups all parts of a swipeable drawer or bottom sheet. Doesn't render its own HTML element.
Inherits `open`, `defaultOpen`, `modal`, `onOpenChange`, `onOpenChangeComplete`, `disablePointerDismissal`, `actionsRef`, `handle`, `triggerId`, `defaultTriggerId`, `children`, `swipeDirection`, `snapPoints`, `snapToSequentialPoints`, `snapPoint`, `defaultSnapPoint`, `onSnapPointChange` from [Base UI Drawer.Root](https://base-ui.com/react/components/drawer#root).
### DrawerBackdrop
An overlay displayed beneath the popup. Renders a `` element.
Inherits `forceRender`, `className`, `render`, `style` from [Base UI Drawer.Backdrop](https://base-ui.com/react/components/drawer#backdrop).
**Data attributes**
| Attribute | Description |
| --------------------- | -------------------------------------------- |
| `data-open` | Present when the drawer is open. |
| `data-closed` | Present when the drawer is closed. |
| `data-starting-style` | Present when the drawer begins animating in. |
| `data-ending-style` | Present when the drawer is animating out. |
**CSS variables**
| Variable | Type | Description |
| ------------------------- | -------- | ----------------------------------------- |
| `--drawer-swipe-progress` | `number` | The swipe progress of the drawer gesture. |
### DrawerClose
Closes the drawer when activated; unstyled so it can be composed via `render` with `Button` or `IconButton`. Renders a `
` element.
Inherits `className`, `render`, `style`, `nativeButton` from [Base UI Drawer.Close](https://base-ui.com/react/components/drawer#close).
**Data attributes**
| Attribute | Description |
| --------------- | ----------------------------------------- |
| `data-disabled` | Whether the button is currently disabled. |
### DrawerContent
A container for the drawer contents. Renders a `` element.
Inherits `className`, `render`, `style` from [Base UI Drawer.Content](https://base-ui.com/react/components/drawer#content).
### DrawerDescription
A paragraph with additional information about the drawer. Renders a `
` element.
Inherits `className`, `render`, `style` from [Base UI Drawer.Description](https://base-ui.com/react/components/drawer#description).
### DrawerIndent
A wrapper element intended to contain your app's main UI. Applies `data-active` when any drawer within the nearest `` is open. Renders a `` element.
Inherits `className`, `render`, `style` from [Base UI Drawer.Indent](https://base-ui.com/react/components/drawer#indent).
**Data attributes**
| Attribute | Description |
| ------------- | ------------------------------------------------------------------ |
| `data-active` | Whether any drawer within the nearest `
` is open. |
### DrawerIndentBackground
An element placed before `` to render a background layer that can be styled based on whether any drawer is open. Renders a `` element.
Inherits `className`, `render`, `style` from [Base UI Drawer.IndentBackground](https://base-ui.com/react/components/drawer#indentbackground).
**Data attributes**
| Attribute | Description |
| ------------- | ------------------------------------------------------------------ |
| `data-active` | Whether any drawer within the nearest `
` is open. |
### DrawerPopup
A container for the drawer contents. Renders a `` element.
Inherits `className`, `render`, `initialFocus`, `finalFocus`, `style` from [Base UI Drawer.Popup](https://base-ui.com/react/components/drawer#popup).
**Data attributes**
| Attribute | Description |
| ---------------------------- | -------------------------------------------------------------------- |
| `data-open` | Present when the drawer is open. |
| `data-closed` | Present when the drawer is closed. |
| `data-starting-style` | Present when the drawer begins animating in. |
| `data-ending-style` | Present when the drawer is animating out. |
| `data-expanded` | Present when the drawer is at the expanded (full-height) snap point. |
| `data-nested-drawer-open` | Present when a nested drawer is open. |
| `data-nested-drawer-swiping` | Present when a nested drawer is being swiped. |
| `data-swipe-dismiss` | Present when the drawer is dismissed by swiping. |
| `data-swipe-direction` | Indicates the swipe direction. |
| `data-swiping` | Present when the drawer is being swiped. |
**CSS variables**
| Variable | Type | Description |
| ---------------------------- | ------------ | ---------------------------------------------------------------------------- |
| `--nested-drawers` | `number` | The number of nested drawers that are currently open. |
| `--drawer-height` | `CSS length` | The height of the drawer popup. |
| `--drawer-frontmost-height` | `CSS length` | The height of the frontmost open drawer in the current nested drawer stack. |
| `--drawer-swipe-movement-x` | `CSS length` | The swipe movement on the X axis. |
| `--drawer-swipe-movement-y` | `CSS length` | The swipe movement on the Y axis. |
| `--drawer-snap-point-offset` | `CSS length` | The snap point offset used for translating the drawer. |
| `--drawer-swipe-strength` | `number` | A scalar (0.1-1) used to scale the swipe release transition duration in CSS. |
### DrawerPortal
A portal element that moves the popup to a different part of the DOM. By default, the portal element is appended to ``. Renders a `
` element.
Inherits `keepMounted`, `container`, `className`, `render`, `style` from [Base UI Drawer.Portal](https://base-ui.com/react/components/drawer#portal).
### DrawerProvider
Provides a shared context for coordinating global Drawer UI, such as indent/background effects based on whether any Drawer is open. Doesn't render its own HTML element.
Inherits `children` from [Base UI Drawer.Provider](https://base-ui.com/react/components/drawer#provider).
### DrawerSwipeArea
An invisible area that listens for swipe gestures to open the drawer. Renders a `
` element.
Inherits `disabled`, `swipeDirection`, `className`, `render`, `style` from [Base UI Drawer.SwipeArea](https://base-ui.com/react/components/drawer#swipearea).
**Data attributes**
| Attribute | Description |
| ---------------------- | ---------------------------------------- |
| `data-open` | Present when the drawer is open. |
| `data-closed` | Present when the drawer is closed. |
| `data-disabled` | Present when the swipe area is disabled. |
| `data-swipe-direction` | Indicates the swipe direction. |
| `data-swiping` | Present when the drawer is being swiped. |
### DrawerTitle
A heading that labels the drawer. Renders an `
` element.
Inherits `className`, `render`, `style` from [Base UI Drawer.Title](https://base-ui.com/react/components/drawer#title).
### DrawerTrigger
A button that opens the drawer. Renders a `` element.
Inherits `handle`, `payload`, `id`, `className`, `render`, `style`, `nativeButton` from [Base UI Drawer.Trigger](https://base-ui.com/react/components/drawer#trigger).
**Data attributes**
| Attribute | Description |
| --------------- | -------------------------------------------------------------------- |
| `data-disabled` | Whether the trigger is currently disabled. |
| `data-open` | Whether the drawer is currently open and was opened by this trigger. |
### DrawerViewport
A positioning container for the drawer popup that can be made scrollable. Renders a `` element.
Inherits `className`, `render`, `style` from [Base UI Drawer.Viewport](https://base-ui.com/react/components/drawer#viewport).
**Data attributes**
| Attribute | Description |
| --------------------- | -------------------------------------------------------- |
| `data-open` | Present when the drawer is open. |
| `data-closed` | Present when the drawer is closed. |
| `data-starting-style` | Present when the drawer begins animating in. |
| `data-ending-style` | Present when the drawer is animating out. |
| `data-nested` | Present when the drawer is nested within another drawer. |
**CSS variables**
| Variable | Type | Description |
| ------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--drawer-keyboard-inset` | `CSS length` | The software keyboard inset, measured from the bottom edge of the layout viewport. Present only when the drawer is wrapped in `Drawer.VirtualKeyboardProvider`. |
### DrawerVirtualKeyboardProvider
Provides keyboard-aware focus and scroll handling for bottom-sheet drawers with form fields.
Inherits `children` from [Base UI Drawer.VirtualKeyboardProvider](https://base-ui.com/react/components/drawer#virtualkeyboardprovider).
### createDrawerHandle
Creates a new handle to connect a Drawer.Root with detached Drawer.Trigger components.
```ts
createDrawerHandle
(): BaseDrawer.Handle
```
**Returns:** `BaseDrawer.Handle`
**Return properties**
| Member | Type | Description |
| ----------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open` | `(triggerId: string \| null) => void` | Opens the dialog, optionally associating it with a trigger. This method should only be called in an event handler or an effect (not during rendering). |
| `openWithPayload` | `(payload: Payload) => void` | Opens the dialog with the given payload, without associating it with any trigger. This method should only be called in an event handler or an effect (not during rendering). |
| `close` | `() => void` | Closes the dialog. This method should only be called in an event handler or an effect (not during rendering). |
| `isOpen` | `boolean` | Whether the dialog is currently open. Returns `false` while no root is attached to the handle. |
# Field
> A form row that ties one control to its label, description and error.
```tsx title="hero.tsx"
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
export function FieldHeroDemo() {
return (
API endpoint
Dify sends extension requests to this base URL.
Enter an API endpoint.
Enter a valid URL, such as https://api.example.com/v1.
)
}
```
## Usage guidelines
- Use `Field` when one control needs a shared `name`, a label, a description, validation or an error. Group several related controls with [`Fieldset`](/components/fieldset.md), and submit fields together with a [`Form`](/components/form.md).
- A `Field` describes one control. A composite that renders its own controls, such as a picker with controls in its popup, does not go inside one.
- Name the control with a visible `FieldLabel`: text inputs, `Textarea`, input-based `Combobox` and `Autocomplete`, a single `Checkbox`, `Switch` and `NumberField`. `Select`, `Slider` and the date and time pickers use their own label parts. A `placeholder` or a tooltip is never the only name.
- `FieldDescription` and `FieldError` describe the control through `aria-describedby`. Do not add a second label or a competing description to the control.
- Set `name` on the `Field`. It keys the value in the submitted form values and the server errors that `Form` maps back to the field.
- Pick one source of validity per rule: native constraint attributes such as `required`, `type` and `minLength`; a `validate` function; or `Form` `errors` from the server. When application code owns validity, set `invalid` on the `Field` and render `FieldError match` only while it is invalid.
See the [forms guide](/guides/forms.md) for the full model.
## Anatomy
```tsx
import {
Field,
FieldDescription,
FieldError,
FieldItem,
FieldLabel,
FieldValidity,
} from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
```
```tsx
```
The control is any dify-ui form control, such as `Input`, `Textarea`, `Checkbox` or `Switch`; it reads its ID, name and validity from the surrounding `Field`. `FieldItem` wraps each checkbox or radio option inside a group, see [Fieldset](/components/fieldset.md). `FieldValidity` passes the current validity state to a render function for custom feedback.
## Examples
### Reading validity state
Native attributes (`required`, `minLength`, `pattern`) drive each matched `FieldError` so every message stays in your own words. `FieldValidity` passes the live validity flags and current value to a render function for custom feedback—such as showing the published URL once the slug is valid. Try `a`, `My Bot` or `support-bot`.
```tsx title="validity.tsx"
import {
Field,
FieldDescription,
FieldError,
FieldLabel,
FieldValidity,
} from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
export function FieldValidityDemo() {
return (
Web app slug
3 to 32 lowercase letters, digits or hyphens.
Enter a web app slug.
Use at least 3 characters.
Use lowercase letters, digits and single hyphens.
{({ validity, value }) => {
const slug = typeof value === 'string' ? value : ''
if (!validity.valid || !slug) return null
return (
Published at /chat/{slug}
)
}}
)
}
```
### Custom validation
`validate` runs after the native constraints pass. Return a message for an invalid value and `null` for a valid one; a `FieldError` without children shows the returned message. This field uses `validationMode="onChange"`, so it checks every keystroke: try `_query`, `sys` or `User Query`. Add `validationDebounceTime` when the check is a request.
```tsx title="custom-validation.tsx"
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
const reservedNames = ['sys', 'env', 'conversation']
export function FieldCustomValidationDemo() {
return (
{
const name = typeof value === 'string' ? value : ''
if (!name) return 'Enter a variable name.'
if (!/^[a-z][a-z0-9_]*$/.test(name))
return 'Use lowercase letters, digits and underscores, starting with a letter.'
if (reservedNames.includes(name)) return `${name} is reserved by Dify.`
return null
}}
>
Variable name
Referenced in prompts as {'{{variable_name}}'}.
)
}
```
### Validity owned by the application
When a form library or other application code decides validity, pass `invalid` to the `Field` and render `FieldError` with `match` while the field is invalid. `match` without a validity key shows the message regardless of state, so the condition belongs to the application. Replace the legacy key with a new `app-` key to clear the error.
```tsx title="external-invalid.tsx"
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'
function getApiKeyError(value: string) {
const trimmed = value.trim()
if (!trimmed) return 'Enter an app API key.'
if (trimmed.startsWith('app-legacy-'))
return 'Legacy keys no longer work. Create a new key and paste it here.'
if (!/^app-[a-z0-9-]+$/i.test(trimmed))
return 'Enter a key starting with app-, using letters, digits or hyphens.'
return null
}
export function FieldExternalInvalidDemo() {
const [apiKey, setApiKey] = React.useState('app-legacy-7f3a9c')
const errorMessage = getApiKeyError(apiKey)
return (
App API key
Find the key under API Access in the app.
{errorMessage && {errorMessage} }
)
}
```
### Checkbox or switch label
For a single checkbox or switch, wrap the control in `FieldLabel` so the whole label toggles it. The description still describes the control.
```tsx title="switch.tsx"
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { Switch } from '@langgenius/dify-ui/switch'
export function FieldSwitchDemo() {
return (
Show citations
Lists the knowledge sources under each answer.
)
}
```
## API reference
### Field
Groups a form control with its label, description, error message, and validation state. Renders a `` element.
Inherits `render`, `style`, `disabled`, `name`, `validate`, `validationMode`, `validationDebounceTime`, `invalid`, `dirty`, `touched`, `actionsRef`, `className` from [Base UI Field.Root](https://base-ui.com/react/components/field#root).
**Data attributes**
| Attribute | Description |
| --------------- | ------------------------------------------- |
| `data-disabled` | Present when the field is disabled. |
| `data-touched` | Present when the field has been touched. |
| `data-dirty` | Present when the field's value has changed. |
| `data-valid` | Present when the field is valid. |
| `data-invalid` | Present when the field is invalid. |
| `data-filled` | Present when the field is filled. |
| `data-focused` | Present when the field control is focused. |
### FieldDescription
A paragraph with additional information about the field. Renders a `
` element.
Inherits `className`, `render`, `style` from [Base UI Field.Description](https://base-ui.com/react/components/field#description).
**Data attributes**
| Attribute | Description |
| --------------- | ---------------------------------------------- |
| `data-disabled` | Present when the field is disabled. |
| `data-valid` | Present when the field is in a valid state. |
| `data-invalid` | Present when the field is in an invalid state. |
| `data-touched` | Present when the field has been touched. |
| `data-dirty` | Present when the field's value has changed. |
| `data-filled` | Present when the field is filled. |
| `data-focused` | Present when the field control is focused. |
### FieldError
An error message displayed if the field control fails validation. Renders a `
` element.
Inherits `match`, `className`, `render`, `style` from [Base UI Field.Error](https://base-ui.com/react/components/field#error).
**Data attributes**
| Attribute | Description |
| --------------------- | --------------------------------------------------- |
| `data-disabled` | Present when the field is disabled. |
| `data-valid` | Present when the field is in a valid state. |
| `data-invalid` | Present when the field is in an invalid state. |
| `data-touched` | Present when the field has been touched. |
| `data-dirty` | Present when the field's value has changed. |
| `data-filled` | Present when the field is filled. |
| `data-focused` | Present when the field control is focused. |
| `data-starting-style` | Present when the error message begins animating in. |
| `data-ending-style` | Present when the error message is animating out. |
### FieldItem
Groups individual items in a checkbox group or radio group with a label and description. Renders a `
` element.
Inherits `disabled`, `className`, `render`, `style` from [Base UI Field.Item](https://base-ui.com/react/components/field#item).
**Data attributes**
| Attribute | Description |
| --------------- | ---------------------------------------------- |
| `data-disabled` | Present when the field is disabled. |
| `data-valid` | Present when the field is in a valid state. |
| `data-invalid` | Present when the field is in an invalid state. |
| `data-touched` | Present when the field has been touched. |
| `data-dirty` | Present when the field's value has changed. |
| `data-filled` | Present when the field is filled. |
| `data-focused` | Present when the field control is focused. |
### FieldLabel
An accessible label that is automatically associated with the field control. Renders a `
` element.
Inherits `nativeLabel`, `className`, `render`, `style` from [Base UI Field.Label](https://base-ui.com/react/components/field#label).
**Data attributes**
| Attribute | Description |
| --------------- | ---------------------------------------------- |
| `data-disabled` | Present when the field is disabled. |
| `data-valid` | Present when the field is in a valid state. |
| `data-invalid` | Present when the field is in an invalid state. |
| `data-touched` | Present when the field has been touched. |
| `data-dirty` | Present when the field's value has changed. |
| `data-filled` | Present when the field is filled. |
| `data-focused` | Present when the field control is focused. |
### FieldValidity
Used to display a custom message based on the field's validity. Requires `children` to be a function that accepts field validity state as an argument.
Inherits `children` from [Base UI Field.Validity](https://base-ui.com/react/components/field#validity).
# Fieldset
> A native fieldset that names a group of related form controls.
```tsx title="hero.tsx"
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { CheckboxGroup } from '@langgenius/dify-ui/checkbox-group'
import { Field, FieldDescription, FieldItem, FieldLabel } from '@langgenius/dify-ui/field'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
const scopes = [
{
label: 'Run apps',
value: 'apps:run',
description: 'Invoke published workflows and chatflows.',
},
{
label: 'Read conversations',
value: 'conversations:read',
description: 'List messages, annotations and feedback logs.',
},
{
label: 'Manage knowledge',
value: 'datasets:write',
description: 'Upload documents and edit indexed chunks.',
},
]
export function FieldsetHeroDemo() {
return (
} className="grid gap-3">
API key scopes
{scopes.map((scope) => (
{scope.label}
{scope.description}
))}
)
}
```
## Usage guidelines
- Use `Fieldset` when one question is answered by several controls: a checkbox or radio group, a multi-thumb slider, or a section of related inputs. A single control uses [`Field`](/components/field.md) alone.
- Name the group with `FieldsetLegend`, and keep a label on every control in it. For checkbox and radio options, wrap each option in a `FieldItem` with its own `FieldLabel`.
- Render the group primitive through `render`, as in `render={ }`, so the group element carries the legend name. Pass `value`, `defaultValue` and change handlers to the group primitive; set `disabled` on the outer `Field` to disable the whole grouped field and its labels, or on a `FieldItem` to disable one option.
- Every `Radio` belongs to a `RadioGroup`. Do not render a standalone `Radio`.
- Wrap a checkbox or radio group in a `Field` with a `name` when the group is one form value. The `Field` submits the selected values and carries the group's `validate` and `FieldError`; see [Form](/components/form.md) for the flow.
## Anatomy
```tsx
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { CheckboxGroup } from '@langgenius/dify-ui/checkbox-group'
import { Field, FieldItem, FieldLabel } from '@langgenius/dify-ui/field'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
```
```tsx
}>
```
A section of separate inputs uses `Fieldset` without `render` and without an outer `Field`; each input keeps its own `Field`.
## Examples
### Radio options with descriptions
A `FieldItem` scopes a label and a description to one option, so each radio is named by its label and described by its own text. Arrow keys move the selection inside the `RadioGroup`.
```tsx title="radio-group.tsx"
import { Field, FieldDescription, FieldItem, FieldLabel } from '@langgenius/dify-ui/field'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
import { Radio, RadioGroup } from '@langgenius/dify-ui/radio-group'
const retrievalModes = [
{
value: 'vector',
label: 'Vector search',
description: 'Finds chunks with a similar meaning to the query.',
},
{
value: 'full-text',
label: 'Full-text search',
description: 'Matches the exact keywords in the query.',
},
{
value: 'hybrid',
label: 'Hybrid search',
description: 'Runs both and reranks the combined results.',
},
]
export function FieldsetRadioGroupDemo() {
return (
}
className="flex-col items-stretch gap-3"
>
Retrieval setting
{retrievalModes.map((mode) => (
{mode.label}
{mode.description}
))}
)
}
```
### Section of related inputs
A plain `Fieldset` groups separate fields under one legend. Each input keeps its own `Field`, label and error.
```tsx title="section.tsx"
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
import { Input } from '@langgenius/dify-ui/input'
export function FieldsetSectionDemo() {
return (
HTTP proxy
Host
Enter a host.
{
const raw = typeof value === 'string' ? value.trim() : ''
if (!raw) return 'Enter a port.'
if (!/^\d+$/.test(raw)) return 'Use digits only.'
const port = Number(raw)
if (port < 1 || port > 65535) return 'Use a port from 1 to 65535.'
return null
}}
>
Port
)
}
```
### Disabled group
Set `disabled` on the outer `Field` so the group, its options and their labels all enter the disabled state. A `FieldDescription` in the outer `Field` explains why and describes every option.
```tsx title="disabled.tsx"
import { Field, FieldDescription, FieldItem, FieldLabel } from '@langgenius/dify-ui/field'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
import { Radio, RadioGroup } from '@langgenius/dify-ui/radio-group'
export function FieldsetDisabledDemo() {
return (
}
className="flex-col items-start gap-2.5"
>
Index method
High quality
Economical
The index method is fixed once a document is embedded with the economical method.
)
}
```
## API reference
### Fieldset
Groups a shared legend with related form controls such as checkbox groups or radio groups. Renders a `` element.
Provides group semantics and labeling; pass interactive state such as `disabled` and `value` to the underlying group primitive.
Inherits `className`, `render`, `style` from [Base UI Fieldset.Root](https://base-ui.com/react/components/fieldset#root).
**Data attributes**
| Attribute | Description |
| --------------- | ----------------------------------------------------- |
| `data-disabled` | Whether the component should ignore user interaction. |
### FieldsetLegend
An accessible label that is automatically associated with the fieldset. Renders a `` element.
Inherits `className`, `render`, `style` from [Base UI Fieldset.Legend](https://base-ui.com/react/components/fieldset#legend).
**Data attributes**
| Attribute | Description |
| --------------- | -------------------------------------- |
| `data-disabled` | Present when the fieldset is disabled. |
# File Drop
> A drop area that receives local files by drag and drop or the file picker.
```tsx title="hero.tsx"
import type { FileDropRejection } from '@langgenius/dify-ui/file-drop'
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import * as React from 'react'
type SelectedFile = {
id: number
file: File
}
const maxFiles = 5
const maxFileSize = 15 * 1024 * 1024
const sizeFormat = new Intl.NumberFormat('en', {
notation: 'compact',
style: 'unit',
unit: 'byte',
unitDisplay: 'narrow',
})
const rejectionLabels: Record
= {
type: 'unsupported type',
count: `over the ${maxFiles}-file limit`,
}
export function FileDropHeroDemo() {
const [files, setFiles] = React.useState([])
const [skipped, setSkipped] = React.useState<{ event: Event; messages: string[] }>()
const nextIdRef = React.useRef(0)
const reportSkipped = (event: Event, messages: string[]) =>
setSkipped((current) =>
current?.event === event
? { event, messages: [...current.messages, ...messages] }
: { event, messages },
)
return (
{
const valid = accepted
.filter((file) => file.size <= maxFileSize)
.map((file) => ({ id: ++nextIdRef.current, file }))
setFiles((current) => [...current, ...valid])
reportSkipped(
event,
accepted
.filter((file) => file.size > maxFileSize)
.map((file) => `${file.name} (over 15 MB)`),
)
}}
onFilesReject={(rejections, { event }) =>
reportSkipped(
event,
rejections.map(({ file, reason }) => `${file.name} (${rejectionLabels[reason]})`),
)
}
render={}
className="flex flex-col items-center gap-1 rounded-xl border border-dashed border-components-dropzone-border bg-components-dropzone-bg px-5 py-6 text-center transition-colors data-dragging:border-components-dropzone-border-accent data-dragging:bg-components-dropzone-bg-accent"
>
Drag documents here, or{' '}
browse
PDF, Markdown, TXT or DOCX. Up to 5 files, 15 MB each.
{skipped && skipped.messages.length > 0 && (
Skipped {skipped.messages.join(', ')}
)}
{files.length > 0 && (
{files.map(({ id, file }) => (
{file.name}
{sizeFormat.format(file.size)}
{
setFiles((current) => current.filter((item) => item.id !== id))
setSkipped(undefined)
}}
>
))}
)}
)
}
```
## Usage guidelines
- **Always include a `FileDropTrigger`**: Dragging needs a pointer. The trigger is the keyboard and screen reader path: it is a button that opens the system file picker, while the hidden file input stays out of the tab order.
- **Name the area and the trigger**: Render the root as a landmark with a name, such as `render={}`, and give the trigger visible text that says what it does.
- **Pick one selection mode**: Without `multiple`, `onFileSelect` receives exactly one file and a selection of several files is rejected as a whole. With `multiple`, `onFilesSelect` receives the accepted files and `maxFiles` keeps the first ones.
- **Report every rejection**: `accept` filters both dropped and picked files. Files that fail it arrive in `onFilesReject` with reason `type`; files over the limit arrive with reason `count`. Show the message in a `role="alert"` element next to the area. With `multiple`, a mixed drop calls `onFilesSelect` first and `onFilesReject` after it, with the same `eventDetails.event`, so one message can cover the whole selection.
- **Check file size yourself**: `FileDrop` checks type and count only. State the accepted types and the size limit in visible text, filter oversized files in `onFilesSelect`, and report them with the other rejections. To cap the total across several selections, pass the remaining slots as `maxFiles`.
- **Keep the files in feature state**: `FileDrop` is not a form control. It does not register with `Field` or `Form`, and its input has no `name`. Store the selected files and send them when the form submits, and validate a missing file in the submit handler.
- **Style the drop state with data attributes**: The root has no surface styles. Use `data-dragging` for the drag highlight and `data-disabled` for the unavailable state; the trigger receives the same attributes.
- **Use `disabled` when uploads are unavailable**: The area refuses drops and the trigger becomes a disabled button. Explain why in nearby text.
- **Folders need `expandDirectories`**: Dropped folders are skipped by default. Set `expandDirectories` to replace each folder with the files inside it, recursively; the same `accept` and count rules apply to the result.
## Anatomy
```tsx
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'
```
```tsx
```
`FileDrop` renders a `` with a hidden `
` inside it. `accept` and `multiple` configure both that input and the drop validation. A drag that carries no files, such as selected text, passes through untouched.
## Examples
### Single file and rejection feedback
Without `multiple`, the area accepts one file. Once a file is chosen, a second `FileDropTrigger` rendered as a `Button` replaces it.
```tsx title="single-file.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'
import * as React from 'react'
export function FileDropSingleFileDemo() {
const [file, setFile] = React.useState
(null)
const [error, setError] = React.useState(null)
return (
{
setFile(selected)
setError(null)
}}
onFilesReject={(rejections) => {
setError(
rejections.some(({ reason }) => reason === 'count')
? 'Drop one CSV file at a time.'
: 'Annotations import only accepts .csv files.',
)
}}
render={}
className="flex min-h-20 items-center gap-3 rounded-xl border border-dashed border-components-dropzone-border bg-components-dropzone-bg px-5 py-4 transition-colors data-dragging:border-components-dropzone-border-accent data-dragging:bg-components-dropzone-bg-accent"
>
{file ? (
{file.name}
}>
Replace file
) : (
Drag a CSV of question and answer pairs here, or{' '}
browse
)}
{error && (
{error}
)}
)
}
```
### Inside a form
Keep the chosen file in state and check for it when the form submits. The submit button stays enabled; submitting without a file shows the error and links it to the trigger with `aria-describedby`. While the package installs, the submit button shows `loading`, repeated submits are ignored and the area is disabled. A rejected package reports in the same error message, and success is announced in a status region.
```tsx title="form.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'
import * as React from 'react'
export function FileDropFormDemo() {
const [file, setFile] = React.useState(null)
const [error, setError] = React.useState(null)
const [status, setStatus] = React.useState<'idle' | 'installing' | 'installed'>('idle')
const errorId = React.useId()
const timerRef = React.useRef(null)
React.useEffect(() => {
return () => {
if (timerRef.current !== null) window.clearTimeout(timerRef.current)
}
}, [])
function install(selected: File) {
setStatus('installing')
setError(null)
timerRef.current = window.setTimeout(() => {
timerRef.current = null
if (selected.size === 0) {
setError(`${selected.name} is empty or damaged.`)
setStatus('idle')
return
}
setStatus('installed')
}, 1000)
}
return (
)
}
```
### Disabled
A disabled area ignores drops and disables its trigger. The surrounding text says why uploads are unavailable.
```tsx title="disabled.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { FileDrop, FileDropTrigger } from '@langgenius/dify-ui/file-drop'
export function FileDropDisabledDemo() {
return (
{}}
render={}
className="flex w-full max-w-md flex-col items-center gap-2 rounded-xl border border-dashed border-components-dropzone-border bg-components-dropzone-bg px-5 py-6 text-center data-disabled:cursor-not-allowed data-disabled:border-divider-regular data-disabled:bg-background-section"
>
Document limit reached for the Sandbox plan
Upgrade to upload more documents.
}>Choose files
)
}
```
## Keyboard
| Key | Action |
| ---------------- | -------------------------------------------------------------------- |
| `Tab` | Moves focus to the trigger. The hidden file input is not a tab stop. |
| `Enter`, `Space` | Opens the system file picker from the trigger. |
## API reference
### FileDrop
Receives local files via drag-and-drop or the system file picker, letting non-file drags pass through untouched. Renders a `` element.
Exposes `data-dragging` and `data-disabled` without imposing surface styles; validates `accept` and file counts unless `validate={false}`.
**Props**
| Prop | Type | Default | Description |
| -------------------- | ------------------------------------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accept?` | `string` | — | Configures the native file picker and, unless `validate={false}`, filters selected files using `
` syntax. |
| `disabled?` | `boolean` | `false` | Whether the component should ignore drops and file picker activation. |
| `expandDirectories?` | `boolean` | — | Replaces each dropped folder with the files inside it, recursively. |
| `multiple?` | `boolean` | `false` | Whether more than one file can be selected. |
| `maxFiles?` | `number` | — | Type-accepted files past this limit are rejected with `count`, keeping the first ones. |
| `validate?` | `boolean` | `true` | Whether selected files are filtered by `accept` and file count. When `false`, every dropped or picked file goes to `onFilesSelect`; `accept` and `multiple` still configure the native file picker. |
| `onFileSelect?` | `((file: File, eventDetails: FileDropEventDetails) => void)` | — | Receives exactly one file. Any multi-file selection is rejected as a whole with `count`. |
| `onFilesSelect?` | `(files: File[], eventDetails: FileDropEventDetails) => void` | — | Receives the accepted files. |
| `onFilesReject?` | `(rejections: FileDropRejection[], eventDetails: FileDropEventDetails) => void` | — | Receives the files rejected by `accept` or the file count. |
Valid prop combinations:
- `multiple: boolean`, `maxFiles?: number`, `validate?: true`, `onFileSelect?: undefined`, `onFilesSelect: (files: File[], eventDetails: FileDropEventDetails) => void`, `onFilesReject?: ((rejections: FileDropRejection[], eventDetails: FileDropEventDetails) => void)`
- `multiple?: false`, `maxFiles?: undefined`, `validate?: true`, `onFileSelect: (file: File, eventDetails: FileDropEventDetails) => void`, `onFilesSelect?: undefined`, `onFilesReject?: ((rejections: FileDropRejection[], eventDetails: FileDropEventDetails) => void)`
- `multiple?: boolean`, `maxFiles?: undefined`, `validate: false`, `onFileSelect?: undefined`, `onFilesSelect: (files: File[], eventDetails: FileDropEventDetails) => void`, `onFilesReject?: undefined`
Inherits `className`, `render`, `style` from [Base UI null](https://base-ui.com/react/handbook/composition).
**Data attributes**
| Attribute | Description |
| --------------- | --------------------------------------------------------- |
| `data-dragging` | Present while files are being dragged over the drop area. |
| `data-disabled` | Present when the drop area is disabled. |
### FileDropTrigger
Opens the system file picker as the keyboard and screen-reader path to the drop area. Renders a `
` element.
Inherits `nativeButton`, `className`, `render`, `style` from [Base UI null](https://base-ui.com/react/handbook/composition).
**Data attributes**
| Attribute | Description |
| --------------- | --------------------------------------------------------- |
| `data-dragging` | Present while files are being dragged over the drop area. |
| `data-disabled` | Present when the drop area is disabled. |
# File Tree
> A nested list of folders and files for browsing and previewing project files.
```tsx title="hero.tsx"
import type { FileTreeIconType } from '@langgenius/dify-ui/file-tree'
import {
FileTree,
FileTreeFile,
FileTreeFolder,
FileTreeFolderPanel,
FileTreeFolderTrigger,
FileTreeIcon,
FileTreeLabel,
FileTreeList,
} from '@langgenius/dify-ui/file-tree'
import * as React from 'react'
type PluginFile = {
path: string
name: string
icon: FileTreeIconType
meta: string
preview: string
}
const providerFiles: PluginFile[] = [
{
path: 'provider/weather.yaml',
name: 'weather.yaml',
icon: 'code',
meta: 'YAML · 6 lines',
preview: `identity:
author: langgenius
name: weather
credentials_for_provider:
api_key:
type: secret-input`,
},
{
path: 'provider/weather.py',
name: 'weather.py',
icon: 'code',
meta: 'Python · 5 lines',
preview: `class WeatherProvider(ToolProvider):
def _validate_credentials(self, credentials):
if not credentials.get("api_key"):
raise ToolProviderCredentialValidationError("Missing key")`,
},
]
const toolFiles: PluginFile[] = [
{
path: 'tools/current_weather.yaml',
name: 'current_weather.yaml',
icon: 'code',
meta: 'YAML · 7 lines',
preview: `identity:
name: current_weather
parameters:
- name: city
type: string
required: true
form: llm`,
},
{
path: 'tools/current_weather.py',
name: 'current_weather.py',
icon: 'code',
meta: 'Python · 5 lines',
preview: `class CurrentWeatherTool(Tool):
def _invoke(self, tool_parameters):
city = tool_parameters["city"]
return self.create_json_message(fetch_current(city))`,
},
{
path: 'tools/forecast.yaml',
name: 'forecast.yaml',
icon: 'code',
meta: 'YAML · 8 lines',
preview: `identity:
name: forecast
parameters:
- name: city
type: string
required: true
- name: days
type: number`,
},
{
path: 'tools/forecast.py',
name: 'forecast.py',
icon: 'code',
meta: 'Python · 5 lines',
preview: `class ForecastTool(Tool):
def _invoke(self, tool_parameters):
days = int(tool_parameters.get("days", 3))
return self.create_json_message(fetch_forecast(days))`,
},
]
const assetFile: PluginFile = {
path: '_assets/icon.svg',
name: 'icon.svg',
icon: 'image',
meta: 'SVG · 412 B',
preview: `
`,
}
const rootFiles: PluginFile[] = [
{
path: 'manifest.yaml',
name: 'manifest.yaml',
icon: 'code',
meta: 'YAML · 6 lines',
preview: `version: 0.4.2
type: plugin
author: langgenius
name: weather
plugins:
tools: [provider/weather.yaml]`,
},
{
path: 'main.py',
name: 'main.py',
icon: 'code',
meta: 'Python · 4 lines',
preview: `from dify_plugin import Plugin, DifyPluginEnv
plugin = Plugin(DifyPluginEnv())
plugin.run()`,
},
{
path: 'requirements.txt',
name: 'requirements.txt',
icon: 'text',
meta: 'Text · 2 lines',
preview: `dify_plugin>=0.2.0,<0.3.0
httpx>=0.27.0`,
},
{
path: 'README.md',
name: 'README.md',
icon: 'markdown',
meta: 'Markdown · 4 lines',
preview: `# Weather plugin
Fetch live weather conditions and multi-day
forecasts inside Dify workflows and agents.`,
},
{
path: 'PRIVACY.md',
name: 'PRIVACY.md',
icon: 'markdown',
meta: 'Markdown · 3 lines',
preview: `# Privacy policy
City names are forwarded to the configured
weather API and are not stored by the plugin.`,
},
]
const filesByPath = new Map(
[assetFile, ...providerFiles, ...toolFiles, ...rootFiles].map((file) => [file.path, file]),
)
export function FileTreeHeroDemo() {
const [selectedPath, setSelectedPath] = React.useState('tools/forecast.yaml')
const selectedFile = filesByPath.get(selectedPath)
const renderFile = ({ path, name, icon }: PluginFile) => (
setSelectedPath(path)}>
{name}
)
return (
_assets
{renderFile(assetFile)}
provider
{providerFiles.map(renderFile)}
tools
{toolFiles.map(renderFile)}
{rootFiles.map(renderFile)}
{selectedFile?.path}
{selectedFile?.meta}
{selectedFile?.preview}
)
}
```
## Usage guidelines
- **Use it to browse and preview files**: Folders are disclosure buttons and files are buttons. The feature owns data loading, routing, renaming, drag and drop and per-item actions.
- **It is not an ARIA tree**: `FileTree` renders a labelled `` of nested lists, not `role="tree"`. Every row is a separate tab stop, and arrow keys, `Home`, `End` and typeahead do not move between rows. Keep trees short enough to tab through, or add a search or filter next to large ones.
- **Name the tree**: Give `FileTree` an `aria-label` or `aria-labelledby` that says what the files belong to, such as "Weather plugin files".
- **Mark the open file with `selected`**: `selected` sets `aria-current="true"` and the highlighted row style. Keep one selected file, driven by the feature's state or route.
- **A file click previews, it does not navigate**: `FileTreeFile` renders a ``. Handle `onClick` to open the preview; do not render a link through it.
- **Use `disabled` for entries that cannot be opened**: A disabled folder keeps its open state but cannot be toggled, and a disabled file leaves the tab order.
- **Let the context set the indent**: Nesting `FileTreeFolderPanel` raises the level and draws one guide per level. Pass `level` only when rendering a row outside its folder, such as a virtualized flat list.
## Anatomy
```tsx
import {
FileTree,
FileTreeBadge,
FileTreeFile,
FileTreeFolder,
FileTreeFolderPanel,
FileTreeFolderTrigger,
FileTreeIcon,
FileTreeLabel,
FileTreeList,
FileTreeMeta,
} from '@langgenius/dify-ui/file-tree'
```
```tsx
```
`FileTreeFolder` is a Base UI Collapsible root rendered as ``; `FileTreeFile` wraps its button in an ` `. `FileTreeIcon` is decorative, so the row's name comes from `FileTreeLabel` and any meta or badge text. Rows render one `FileTreeGuide` per nesting level themselves; render it directly only in a custom row.
## Examples
### Rendering from data
Render folders and files recursively from the feature's data. `FileTreeMeta` adds a short status after the label and `FileTreeBadge` a compact value such as a size. Both become part of the row's accessible name.
```tsx title="data-driven.tsx"
import type { FileTreeIconType } from '@langgenius/dify-ui/file-tree'
import {
FileTree,
FileTreeBadge,
FileTreeFile,
FileTreeFolder,
FileTreeFolderPanel,
FileTreeFolderTrigger,
FileTreeIcon,
FileTreeLabel,
FileTreeList,
FileTreeMeta,
} from '@langgenius/dify-ui/file-tree'
import * as React from 'react'
type DocumentNode = {
id: string
name: string
icon: FileTreeIconType
meta?: string
badge?: string
children?: DocumentNode[]
}
const documents: DocumentNode[] = [
{
id: 'product',
name: 'product-docs',
icon: 'folder',
children: [
{ id: 'getting-started', name: 'getting-started.md', icon: 'markdown' },
{ id: 'api-reference', name: 'api-reference.pdf', icon: 'pdf', badge: '12 MB' },
{
id: 'guides',
name: 'guides',
icon: 'folder',
children: [
{ id: 'rag-pipeline', name: 'rag-pipeline.md', icon: 'markdown' },
{
id: 'agent-strategies',
name: 'agent-strategies.md',
icon: 'markdown',
meta: 'indexing',
},
],
},
],
},
{
id: 'support',
name: 'support',
icon: 'folder',
children: [
{ id: 'faq', name: 'faq.csv', icon: 'table' },
{ id: 'pricing', name: 'pricing.xlsx', icon: 'table' },
],
},
{ id: 'changelog', name: 'changelog.txt', icon: 'text' },
{ id: 'export', name: 'workspace-export.zip', icon: 'archive', badge: '48 MB' },
]
export function FileTreeDataDrivenDemo() {
const [selectedId, setSelectedId] = React.useState('getting-started')
const renderNodes = (nodes: DocumentNode[]) =>
nodes.map((node) =>
node.children ? (
{node.name}
{renderNodes(node.children)}
) : (
setSelectedId(node.id)}
>
{node.name}
{node.meta && {node.meta} }
{node.badge && {node.badge} }
),
)
return (
{renderNodes(documents)}
)
}
```
### Controlled folders
Pass `open` and `onOpenChange` to `FileTreeFolder` when something outside the tree opens folders, such as an expand-all action or revealing the file that is open in the editor.
```tsx title="controlled.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
FileTree,
FileTreeFile,
FileTreeFolder,
FileTreeFolderPanel,
FileTreeFolderTrigger,
FileTreeIcon,
FileTreeLabel,
FileTreeList,
} from '@langgenius/dify-ui/file-tree'
import * as React from 'react'
const folders = [
{ name: 'nodes', files: ['llm.json', 'knowledge-retrieval.json', 'code.json'] },
{ name: 'variables', files: ['environment.json', 'conversation.json'] },
]
export function FileTreeControlledDemo() {
const [openFolders, setOpenFolders] = React.useState(['nodes'])
const [selectedFile, setSelectedFile] = React.useState('nodes/llm.json')
const allOpen = openFolders.length === folders.length
const titleId = React.useId()
return (
Workflow files
setOpenFolders(allOpen ? [] : folders.map(({ name }) => name))}
>
{allOpen ? 'Collapse all' : 'Expand all'}
{folders.map(({ name, files }) => (
setOpenFolders((current) =>
open ? [...current, name] : current.filter((folder) => folder !== name),
)
}
>
{name}
{files.map((file) => {
const path = `${name}/${file}`
return (
setSelectedFile(path)}
>
{file}
)
})}
))}
setSelectedFile('workflow.yml')}
>
workflow.yml
)
}
```
### Disabled entries
A disabled folder keeps its current open or closed state and cannot be toggled, while a disabled file cannot be opened. Explain why with `FileTreeMeta` when the reason is not obvious.
```tsx title="disabled.tsx"
import {
FileTree,
FileTreeFile,
FileTreeFolder,
FileTreeFolderPanel,
FileTreeFolderTrigger,
FileTreeIcon,
FileTreeLabel,
FileTreeList,
FileTreeMeta,
} from '@langgenius/dify-ui/file-tree'
import * as React from 'react'
export function FileTreeDisabledDemo() {
const [selectedFile, setSelectedFile] = React.useState('manifest.yaml')
return (
.venv
generated
schemas
locked open
setSelectedFile('schemas/input.json')}
>
input.json
setSelectedFile('manifest.yaml')}
>
manifest.yaml
.env
hidden
)
}
```
## Keyboard
| Key | Action |
| ---------------- | --------------------------------------------------------------------------------------- |
| `Tab` | Moves focus to the next visible folder or file. Disabled folders and files are skipped. |
| `Shift` + `Tab` | Moves focus to the previous visible folder or file. |
| `Enter`, `Space` | On a folder, expands or collapses it. On a file, activates it. |
## API reference
### FileTree
A composable hierarchical file list built with Base UI Collapsible. Renders a `` element.
Folders are disclosure buttons and files are preview buttons; feature code owns data loading, routing, and item actions.
Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).
### FileTreeBadge
Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).
### FileTreeFile
**Props**
| Prop | Type | Default | Description |
| ----------- | --------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `level?` | `number` | — | The nesting depth of the row, starting at 1, which sets its indentation guides. Inferred from the surrounding folders when omitted. |
| `selected?` | `boolean` | `false` | Whether the file is the currently selected one, marked with `aria-current`. |
Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).
**Data attributes**
| Attribute | Description |
| --------------- | ------------------------------------------ |
| `data-selected` | Present when the file is the selected row. |
| `data-disabled` | Present when the file is disabled. |
### FileTreeFolder
Groups all parts of the collapsible. Renders a `` element.
Inherits `className`, `open`, `defaultOpen`, `onOpenChange`, `disabled`, `render`, `style` from [Base UI Collapsible.Root](https://base-ui.com/react/components/collapsible#root).
**Data attributes**
| Attribute | Description |
| --------------------- | ------------------------------------------------- |
| `data-open` | Present when the collapsible is open. |
| `data-closed` | Present when the collapsible is closed. |
| `data-starting-style` | Present when the collapsible begins animating in. |
| `data-ending-style` | Present when the collapsible is animating out. |
### FileTreeFolderPanel
A panel with the collapsible contents. Renders a `
` element.
Inherits `hiddenUntilFound`, `keepMounted`, `className`, `render`, `style` from [Base UI Collapsible.Panel](https://base-ui.com/react/components/collapsible#panel).
**Data attributes**
| Attribute | Description |
| --------------------- | --------------------------------------------- |
| `data-open` | Present when the collapsible panel is open. |
| `data-closed` | Present when the collapsible panel is closed. |
| `data-starting-style` | Present when the panel begins animating in. |
| `data-ending-style` | Present when the panel is animating out. |
**CSS variables**
| Variable | Type | Description |
| ---------------------------- | -------- | ------------------------------- |
| `--collapsible-panel-height` | `number` | The collapsible panel's height. |
| `--collapsible-panel-width` | `number` | The collapsible panel's width. |
### FileTreeFolderTrigger
A button that opens and closes the collapsible panel. Renders a `
` element.
**Props**
| Prop | Type | Default | Description |
| -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `level?` | `number` | — | The nesting depth of the row, starting at 1, which sets its indentation guides. Inferred from the surrounding folders when omitted. |
Inherits `className`, `render`, `style`, `nativeButton` from [Base UI Collapsible.Trigger](https://base-ui.com/react/components/collapsible#trigger).
**Data attributes**
| Attribute | Description |
| ----------------- | ------------------------------------------- |
| `data-panel-open` | Present when the collapsible panel is open. |
### FileTreeGuide
Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).
### FileTreeIcon
**Props**
| Prop | Type | Default | Description |
| ----------- | -------------------------------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------- |
| `type?` | `'archive' \| 'code' \| 'database' \| 'file' \| 'folder' \| 'image' \| 'json' \| 'markdown' \| 'pdf' \| 'table' \| 'text'` | `'file'` | The kind of file the icon represents. `'folder'` switches between closed and open icons with the surrounding folder. |
| `children?` | `React.ReactNode` | — | A custom icon that replaces the one chosen by `type`. |
Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).
### FileTreeLabel
Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).
### FileTreeList
Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).
### FileTreeMeta
Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).
# Form
> A native form boundary that submits values and shows field errors.
```tsx title="hero.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { Textarea } from '@langgenius/dify-ui/textarea'
import * as React from 'react'
type AppSettingsValues = {
appName: string
description: string
}
export function FormHeroDemo() {
const [saved, setSaved] = React.useState(null)
return (
)
}
```
## Usage guidelines
- Wrap every group of controls that saves together in a real form. `Form` renders a native ``; use it when the boundary needs `onFormSubmit` values, server `errors`, `validationMode` or `actionsRef`. A native ` ` stays correct when another form library owns submission and validation. Do not nest form owners.
- Give every submit button `type="submit"` and keep it enabled while the form is incomplete: submitting runs validation and marks the fields. Show `loading` on the button while the request is pending.
- Put a `name` on each [`Field`](/components/field.md). The names are the keys of the values object passed to `onFormSubmit` and of the `errors` object.
- Report a rejected submission at the field it concerns: map a documented error code to that field's message in `errors`, rather than showing the raw server message or a toast. A rejection that belongs to no field stays inside the form as an [`Alert`](/components/alert.md).
- Keep drafts, schemas and reset behavior in the application owner. Prefer uncontrolled controls with `defaultValue` unless application code must own the value while editing.
- Name each form with `aria-label` or `aria-labelledby` when a page has more than one.
Single fields are covered on [Field](/components/field.md) and grouped controls on [Fieldset](/components/fieldset.md).
## Anatomy
```tsx
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { Button } from '@langgenius/dify-ui/button'
```
```tsx
```
## Examples
### Submitting values
`onFormSubmit` receives the values as an object keyed by field `name`, and calls `preventDefault` on the native submit event. With the default `validationMode="onSubmit"`, submitting validates every field first:
1. Native constraints run, then each `validate` function.
2. When a field is invalid, its `FieldError` shows, the control gets `aria-invalid`, focus moves to the first invalid control, and `onFormSubmit` is not called.
3. After the first submission, every field validates on each change: an error clears as soon as the value is fixed, and emptying a required field shows its error right away.
Submit the empty form to see the flow, then fill it in to see the submitted values.
```tsx title="submit.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { CheckboxGroup } from '@langgenius/dify-ui/checkbox-group'
import {
Field,
FieldDescription,
FieldError,
FieldItem,
FieldLabel,
} from '@langgenius/dify-ui/field'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'
type ApiKeyValues = {
name: string
scopes: string[]
}
const scopes = [
{ label: 'Run apps', value: 'apps:run' },
{ label: 'Read conversations', value: 'conversations:read' },
{ label: 'Manage knowledge', value: 'datasets:write' },
]
export function FormSubmitDemo() {
const [submitted, setSubmitted] = React.useState()
return (
aria-label="Create API key"
className="grid gap-4"
onSubmitCapture={() => setSubmitted(undefined)}
onFormSubmit={(values) => setSubmitted(values)}
>
Key name
Only visible to workspace admins.
Enter a key name.
Array.isArray(value) && value.length > 0 ? null : 'Choose at least one scope.'
}
>
} className="grid gap-1.5">
Scopes
{scopes.map((scope) => (
{scope.label}
))}
Create key
{submitted && (
{JSON.stringify(submitted, null, 2)}
)}
)
}
```
### Server errors
Pass `errors` to map a rejected request to fields by `name`. The error shows at once in a `FieldError` without `match`, the control becomes invalid and receives focus, and the error clears when the user edits that field. Submitting again without an edit keeps the error and does not call `onFormSubmit`. Save with the default key to see the rejection, then enter a key that starts with `sk-`.
```tsx title="server-errors.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'
type CredentialValues = {
baseUrl: string
apiKey: string
}
function saveCredentials(values: CredentialValues, signal: AbortSignal) {
return new Promise<{ code: 'invalid_api_key' | 'ok' }>((resolve, reject) => {
const timer = setTimeout(() => {
if (!values.apiKey.startsWith('sk-')) resolve({ code: 'invalid_api_key' })
else resolve({ code: 'ok' })
}, 800)
signal.addEventListener(
'abort',
() => {
clearTimeout(timer)
reject(new DOMException('Aborted', 'AbortError'))
},
{ once: true },
)
})
}
export function FormServerErrorsDemo() {
const [errors, setErrors] = React.useState>({})
const [status, setStatus] = React.useState<'idle' | 'saving' | 'saved'>('idle')
const controllerRef = React.useRef(null)
React.useEffect(() => () => controllerRef.current?.abort(), [])
async function submit(values: CredentialValues) {
if (status === 'saving') return
controllerRef.current?.abort()
const controller = new AbortController()
controllerRef.current = controller
setStatus('saving')
try {
const result = await saveCredentials(values, controller.signal)
if (result.code === 'invalid_api_key') {
setErrors({ apiKey: 'OpenAI rejected this key. Check that it is active.' })
setStatus('idle')
return
}
setErrors({})
setStatus('saved')
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError') return
setStatus('idle')
}
}
return (
aria-label="OpenAI credentials"
className="grid w-full max-w-96 gap-4"
errors={errors}
onChange={() => {
if (status === 'saved') setStatus('idle')
}}
onFormSubmit={(values) => void submit(values)}
>
API base URL
Enter the API base URL.
Enter a valid URL, such as https://api.openai.com/v1.
(value ? null : 'Enter an API key.')}>
API key
Keys start with sk-.
{status === 'saved' ? 'Credentials saved' : ''}
Save
)
}
```
### Validation timing
`validationMode` on `Form` sets when fields validate; a `validationMode` on a `Field` takes precedence. With `onBlur`, a field validates when focus leaves it; an empty required field is flagged only after the user has edited it, and typing hides the error until the next blur. `onChange` validates on every change. In every mode, submitting validates all fields, including untouched required ones. Switch between the modes below to compare when errors appear and clear.
```tsx title="validation-mode.tsx"
import type { FormProps } from '@langgenius/dify-ui/form'
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
import * as React from 'react'
type ValidationMode = NonNullable
const modes: ValidationMode[] = ['onSubmit', 'onBlur', 'onChange']
export function FormValidationModeDemo() {
const [mode, setMode] = React.useState('onBlur')
const [invitedEmail, setInvitedEmail] = React.useState()
const modeLabelId = React.useId()
return (
)
}
```
## Keyboard
| Key | Action |
| ------- | --------------------------------------------------------------------------------------------------------- |
| `Enter` | In a text input, submits the form. Invalid fields show their errors and focus moves to the first of them. |
## API reference
### Form
A native form element with consolidated client and server error handling. Renders a `` element.
Inherits `className`, `render`, `style`, `validationMode`, `errors`, `onFormSubmit`, `actionsRef` from [Base UI Form](https://base-ui.com/react/components/form).
# Icon Button
> An icon-only command button with a required accessible name.
```tsx title="hero.tsx"
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Separator } from '@langgenius/dify-ui/separator'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@langgenius/dify-ui/tooltip'
const actions = [
{ label: 'Run this step', icon: 'i-ri-play-large-line' },
{ label: 'View logs', icon: 'i-ri-file-list-3-line' },
{ label: 'Duplicate node', icon: 'i-ri-file-copy-line' },
] as const
export function IconButtonHeroDemo() {
return (
{actions.map(({ label, icon }) => (
}
/>
{label}
))}
)
}
```
## Usage guidelines
- Use `IconButton` for a command shown as one icon with no visible text. An action with a visible label, with or without an icon, uses [`Button`](/components/button.md); navigation stays on a native link.
- Give every icon button exactly one accessible-name source: `aria-label`, or `aria-labelledby` when suitable visible text exists elsewhere. The types reject a button with neither or both.
- Pair most icon buttons with a [`Tooltip`](/components/tooltip.md) that shows the same words as the name. Compose it through the `render` prop of `TooltipTrigger`. A close (X) button and a "more" menu button go without one, because their icons are universally understood.
- A tooltip is a visual hint, never the accessible name. Keep `aria-label` or `aria-labelledby` on the button even when a tooltip shows the same text.
- Pass exactly one React element as the child: the glyph, with `aria-hidden="true"`. The child owns the glyph and its optical size; `IconButton` owns the button size, radius, colors, hover, disabled and focus-visible styles.
- Omit `variant` for the neutral icon-button appearance. The other variants match `Button`. Use `tone="destructive"` for destructive intent; the accent variants do not take it.
- Use `className` for external layout or for selectors driven by a composed primitive, such as `data-pressed` or `data-popup-open`. Do not recreate an existing variant with classes.
- When `Toggle`, `Menu`, `Popover`, `Tooltip` or `Collapsible` owns the interaction state, keep that primitive outside and compose `IconButton` through its `render` prop. The owner keeps its pressed, open and expanded state, events and ref; do not mirror that state on the icon button.
- Do not render navigation through `IconButton`, whose button behavior is for commands. Put `iconButtonVariants` on a native anchor or router link, which owns its own name and navigation.
## Anatomy
```tsx
import { IconButton, iconButtonVariants } from '@langgenius/dify-ui/icon-button'
```
```tsx
```
## Examples
### Variants and tones
The default variant is neutral and suits dense toolbars. `primary`, `secondary`, `secondary-accent`, `tertiary`, `ghost` and `ghost-accent` match `Button`. Every variant except the two accent ones also takes `tone="destructive"`. A disabled button keeps its variant and dims.
```tsx title="variants.tsx"
import { IconButton } from '@langgenius/dify-ui/icon-button'
import * as React from 'react'
const defaultVariants = [
{ variant: 'default', label: 'Edit (default)', icon: 'i-ri-edit-line' },
{ variant: 'primary', label: 'Create (primary)', icon: 'i-ri-add-line' },
{ variant: 'secondary', label: 'Refresh (secondary)', icon: 'i-ri-refresh-line' },
{ variant: 'tertiary', label: 'Filter (tertiary)', icon: 'i-ri-filter-3-line' },
{ variant: 'ghost', label: 'Expand (ghost)', icon: 'i-ri-expand-diagonal-line' },
] as const
const accentVariants = [
{ variant: 'secondary-accent', label: 'Share (secondary-accent)', icon: 'i-ri-share-line' },
{
variant: 'ghost-accent',
label: 'Generate with AI (ghost-accent)',
icon: 'i-ri-sparkling-line',
},
] as const
const destructiveVariants = [
{ variant: 'default', label: 'Delete (default destructive)' },
{ variant: 'primary', label: 'Delete (primary destructive)' },
{ variant: 'secondary', label: 'Delete (secondary destructive)' },
{ variant: 'tertiary', label: 'Delete (tertiary destructive)' },
{ variant: 'ghost', label: 'Delete (ghost destructive)' },
] as const
const disabledVariants = [
{ variant: 'default', label: 'Disabled (default)' },
{ variant: 'primary', label: 'Disabled (primary)' },
{ variant: 'secondary', label: 'Disabled (secondary)' },
{ variant: 'tertiary', label: 'Disabled (tertiary)' },
] as const
export function IconButtonVariantsDemo() {
const defaultId = React.useId()
const accentId = React.useId()
const destructiveId = React.useId()
const disabledId = React.useId()
return (
Default
{defaultVariants.map(({ variant, label, icon }) => (
{variant}
))}
Accent
{accentVariants.map(({ variant, label, icon }) => (
{variant}
))}
Destructive
{destructiveVariants.map(({ variant, label }) => (
{variant}
))}
Disabled
{disabledVariants.map(({ variant, label }) => (
{variant}
))}
)
}
```
### Sizes
`xs` through `xl` set the button box and radius. Size the glyph in its own class; the larger sizes fit a `size-4` or `size-5` icon.
```tsx title="sizes.tsx"
import { IconButton } from '@langgenius/dify-ui/icon-button'
const sizes = [
{ size: 'xs', icon: 'size-3' },
{ size: 'sm', icon: 'size-3.5' },
{ size: 'md', icon: 'size-4' },
{ size: 'lg', icon: 'size-4' },
{ size: 'xl', icon: 'size-5' },
] as const
export function IconButtonSizesDemo() {
return (
{sizes.map(({ size, icon }) => (
{size}
))}
)
}
```
### Composing with a stateful primitive
`Toggle` owns the pressed state of the pin button and `Menu` owns the open state of the "more" button; each renders `IconButton` through `render`. The pin button keeps a constant name and reports its state through `aria-pressed`. The "more" button has no tooltip.
```tsx title="composition.tsx"
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from '@langgenius/dify-ui/menu'
import { Toggle } from '@langgenius/dify-ui/toggle'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
export function IconButtonCompositionDemo() {
return (
}
/>
}
/>
Pin app
}
/>
Duplicate
Export DSL
Delete
)
}
```
### Icon link
A link that looks like an icon button stays a native anchor with the classes from `iconButtonVariants`. The anchor carries its own `aria-label`.
```tsx title="link.tsx"
import { iconButtonVariants } from '@langgenius/dify-ui/icon-button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
export function IconButtonLinkDemo() {
return (
}
/>
Dify documentation
)
}
```
## Keyboard
| Key | Action |
| ---------------- | -------------------------------------------------------------------------------------------------------------- |
| `Enter`, `Space` | Activates the button. |
| `Tab` | Moves focus to the next control. A disabled button leaves the tab order unless `focusableWhenDisabled` is set. |
## API reference
### IconButton
An icon-only command button that requires a single icon element and an accessible name. Renders a `` element.
Requires `aria-label` or `aria-labelledby`.
**Props**
| Prop | Type | Default | Description |
| ------------------ | -------------------------------------------------------------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------- |
| `aria-label?` | `string` | — | Names the element for assistive technology. Pass either this or `aria-labelledby`. |
| `aria-labelledby?` | `string` | — | Identifies the element that names this one. Pass either this or `aria-label`. |
| `size?` | `'lg' \| 'md' \| 'sm' \| 'xl' \| 'xs'` | `'md'` | The square size of the button. |
| `variant?` | `'default' \| 'ghost' \| 'ghost-accent' \| 'primary' \| 'secondary' \| 'secondary-accent' \| 'tertiary'` | `'default'` | The visual emphasis of the button. The accent variants cannot be combined with `tone="destructive"`. |
| `tone?` | `'default' \| 'destructive'` | `'default'` | Whether the button represents a destructive action. |
| `children` | `React.ReactElement>` | — | A single decorative icon element. Hide it from assistive technology with `aria-hidden`. |
Valid prop combinations:
- `aria-label: string`, `aria-labelledby?: undefined`, `variant?: 'default' | 'ghost' | 'primary' | 'secondary' | 'tertiary'`, `tone?: 'default' | 'destructive'`
- `aria-label: string`, `aria-labelledby?: undefined`, `variant: 'ghost-accent' | 'secondary-accent'`, `tone?: 'default'`
- `aria-label?: undefined`, `aria-labelledby: string`, `variant?: 'default' | 'ghost' | 'primary' | 'secondary' | 'tertiary'`, `tone?: 'default' | 'destructive'`
- `aria-label?: undefined`, `aria-labelledby: string`, `variant: 'ghost-accent' | 'secondary-accent'`, `tone?: 'default'`
Inherits `className`, `render`, `style`, `nativeButton`, `focusableWhenDisabled` from [Base UI Button](https://base-ui.com/react/components/button).
**Data attributes**
| Attribute | Description |
| --------------- | ------------------------------------ |
| `data-disabled` | Present when the button is disabled. |
### iconButtonVariants
```ts
iconButtonVariants(
props?: (ConfigVariants<{ variant: { default: string[]; primary: string[]; secondary: string[]; 'secondary-accent': string[]; tertiary: string[]; ghost: string[]; 'ghost-accent': string[]; }; tone: { default: string; destructive: string; }; size: { xs: string; sm: string; md: string; lg: string; xl: string; }; }> & ClassProp),
): string
```
**Parameters**
| Parameter | Type | Description |
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| `props?` | `(ConfigVariants<{ variant: { default: string[]; primary: string[]; secondary: string[]; 'secondary-accent': string[]; tertiary: string[]; ghost: string[]; 'ghost-accent': string[]; }; tone: { default: string; destructive: string; }; size: { xs: string; sm: string; md: string; lg: string; xl: string; }; }> & ClassProp)` | — |
**Returns:** `string`
# Infotip
> An information icon that opens a short explanation on hover, click or touch.
```tsx title="hero.tsx"
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import * as React from 'react'
export function InfotipHeroDemo() {
const labelId = React.useId()
return (
Chunk overlap
Repeats the end of each chunk at the start of the next one, so sentences that cross a
boundary keep their context.
)
}
```
## Usage guidelines
- Use `Infotip` when an information icon's primary action is opening an explanation. Use `Tooltip` when the trigger already has another primary action and only needs a visual hint.
- `Infotip` is a popover: it opens on hover, click, touch and keyboard activation, so its content reaches every user and can hold links.
- Name the trigger with `aria-labelledby` when a visible topic exists, otherwise with a short `aria-label`. The trigger needs its name while the popup is closed, so it never comes from the popup content.
- Name the popup with the same short topic, through `aria-labelledby`, `aria-label` or an `InfotipTitle`. Do not copy the explanation into either name, and keep the body as normal children rather than turning it into the dialog's description.
- `InfotipTrigger` stops click propagation, so an infotip inside a clickable row or card does not trigger the enclosing action.
- `Infotip` owns its surface, spacing, typography, radius and shadow. Callers may constrain the width or keep intentional line breaks, and may place and color the trigger, but do not resize it; use `size`.
## Anatomy
```tsx
import { Infotip, InfotipContent, InfotipTitle, InfotipTrigger } from '@langgenius/dify-ui/infotip'
```
```tsx
```
`InfotipTrigger` renders the icon button itself and takes no children; `iconVariant` picks its glyph: `question` (the default), `information` or `warning`. `InfotipContent` bundles the portal, positioner and popup, and opens on the `top` side by default.
## Examples
### Named by a title
When adjacent text states a value rather than the topic, `InfotipTitle` gives the dialog its name while the trigger carries a matching `aria-label`.
```tsx title="title.tsx"
import { Infotip, InfotipContent, InfotipTitle, InfotipTrigger } from '@langgenius/dify-ui/infotip'
export function InfotipTitleDemo() {
return (
High priority
Processing priority
Documents with a higher priority are indexed first when several are waiting.
)
}
```
### Links in the explanation
The popup can hold interactive content. Opening it from the keyboard moves focus to the first link.
```tsx title="link.tsx"
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import * as React from 'react'
export function InfotipLinkDemo() {
const labelId = React.useId()
return (
)
}
```
### Icon variants
`iconVariant` selects the trigger glyph: `question` for general help, `information` for factual details and `warning` for caveats.
```tsx title="icon-variants.tsx"
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import * as React from 'react'
const variants = [
{
iconVariant: 'question',
topic: 'Top K',
explanation: 'The number of chunks returned for each query.',
},
{
iconVariant: 'information',
topic: 'Model context',
explanation: 'Includes retrieved chunks, system instructions and recent conversation turns.',
},
{
iconVariant: 'warning',
topic: 'Legacy indexing',
explanation: 'Keyword-only indexing skips semantic search and reduces recall on long queries.',
},
] as const
function VariantRow({ iconVariant, topic, explanation }: (typeof variants)[number]) {
const labelId = React.useId()
return (
{topic}
{explanation}
{iconVariant}
)
}
export function InfotipIconVariantsDemo() {
return (
{variants.map((variant) => (
))}
)
}
```
### Sizes
`size` sets the icon and the trigger's layout box together: `sm` (12px), `md` (16px, the default) and `lg` (16px with a larger icon). Every size keeps a 24px pointer target outside its layout box, so the larger target does not move the surrounding content. An ancestor that clips overflow also clips that target.
```tsx title="sizes.tsx"
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import * as React from 'react'
const rows = [
{
size: 'sm',
topic: 'Top K',
explanation: 'The number of chunks returned for each query.',
textClassName: 'system-xs-medium',
},
{
size: 'md',
topic: 'Score threshold',
explanation: 'Chunks scoring below this similarity are left out of the results.',
textClassName: 'system-sm-medium',
},
{
size: 'lg',
topic: 'Rerank model',
explanation: 'Reorders the retrieved chunks by relevance before they reach the model.',
textClassName: 'system-md-medium',
},
] as const
function SizeRow({ size, topic, explanation, textClassName }: (typeof rows)[number]) {
const labelId = React.useId()
return (
{topic}
{explanation}
{size}
)
}
export function InfotipSizesDemo() {
return (
)
}
```
## Keyboard
| Key | Action |
| ---------------- | ----------------------------------------------------------------------------------------------------------- |
| `Enter`, `Space` | Opens the infotip from a focused trigger and moves focus into the popup, to its first link when it has one. |
| `Tab` | Moves focus past the popup's last link to the next control on the page and closes the popup. |
| `Escape` | Closes the infotip and returns focus to the trigger. |
## API reference
### Infotip
Groups an icon button trigger and an accessible explanation popover. Doesn't render its own HTML element.
Opens on hover, click, touch, or keyboard activation and supports interactive content such as links.
Inherits `defaultOpen`, `open`, `onOpenChange`, `onOpenChangeComplete`, `actionsRef`, `modal`, `triggerId`, `defaultTriggerId`, `children` from [Base UI Popover.Root](https://base-ui.com/react/components/popover#root).
### InfotipContent
A container for the popover contents. Renders a `` element.
**Props**
| Prop | Type | Default | Description |
| ------------- | -------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------- |
| `side?` | `'bottom' \| 'inline-end' \| 'inline-start' \| 'left' \| 'right' \| 'top'` | `'top'` | Which side of the trigger to place the popup against. May automatically change to avoid collisions. |
| `sideOffset?` | `number \| OffsetFunction` | `8` | Distance between the anchor and the popup in pixels. Also accepts a function that returns the distance. |
| `children` | `React.ReactNode` | — | The explanation content. |
Inherits `className`, `render`, `style`, `initialFocus`, `finalFocus`, `align`, `alignOffset` from [Base UI Popover.Popup](https://base-ui.com/react/components/popover#popup).
**Data attributes**
| Attribute | Description |
| --------------------- | --------------------------------------------------------------------- |
| `data-open` | Present when the popup is open. |
| `data-closed` | Present when the popup is closed. |
| `data-starting-style` | Present when the popup begins animating in. |
| `data-ending-style` | Present when the popup is animating out. |
| `data-side` | Indicates which side the popup is positioned relative to the trigger. |
| `data-align` | Indicates how the popup is aligned relative to specified side. |
| `data-instant` | Present if animations should be instant. |
**CSS variables**
| Variable | Type | Description |
| --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `--popup-width` | — | The width of the popup. |
| `--popup-height` | — | The height of the popup. |
| `--available-width` | `number` | The available width between the trigger and the edge of the viewport. |
| `--available-height` | `number` | The available height between the trigger and the edge of the viewport. |
| `--anchor-width` | `number` | The anchor's width. |
| `--anchor-height` | `number` | The anchor's height. |
| `--transform-origin` | `string` | The coordinates that this element is anchored to. Used for animations and transitions. |
| `--positioner-width` | `number` | The width of the popover's positioner. It is important to set `width` to this value when using CSS to animate size changes. |
| `--positioner-height` | `number` | The height of the popover's positioner. It is important to set `height` to this value when using CSS to animate size changes. |
### InfotipTitle
A heading that labels the popover. Renders an `
` element.
Inherits `className`, `render`, `style` from [Base UI Popover.Title](https://base-ui.com/react/components/popover#title).
### InfotipTrigger
An icon button that opens the infotip on hover or click and stops click propagation; requires `aria-label` or `aria-labelledby`. Renders a `` element.
**Props**
| Prop | Type | Default | Description |
| ------------------ | ------------------------------------------ | ------------ | ------------------------------------------------------------------------------------- |
| `aria-label?` | `string` | — | Names the element for assistive technology. Pass either this or `aria-labelledby`. |
| `aria-labelledby?` | `string` | — | Identifies the element that names this one. Pass either this or `aria-label`. |
| `iconVariant?` | `'information' \| 'question' \| 'warning'` | `'question'` | The icon shown in the trigger. |
| `size?` | `'lg' \| 'md' \| 'sm'` | `'md'` | The size of the trigger and its icon. |
| `openOnHover?` | `boolean` | `true` | Whether the infotip also opens when the trigger is hovered. |
| `closeDelay?` | `number` | `200` | How long to wait before closing an infotip that was opened on hover, in milliseconds. |
Valid prop combinations:
- `aria-label: string`, `aria-labelledby?: undefined`
- `aria-label?: undefined`, `aria-labelledby: string`
Inherits `id`, `className`, `style`, `payload`, `delay` from [Base UI Popover.Trigger](https://base-ui.com/react/components/popover#trigger).
**Data attributes**
| Attribute | Description |
| ----------------- | ----------------------------------------------- |
| `data-popup-open` | Present when the corresponding popover is open. |
| `data-pressed` | Present when the trigger is pressed. |
| `data-disabled` | Present when the trigger is disabled. |
# Input
> A single-line text input that takes its label and validation from Field.
```tsx title="hero.tsx"
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
export function InputHeroDemo() {
return (
App name
Shown in the app list and on the published WebApp.
)
}
```
## Usage guidelines
- Use `Input` for one line of free text. Multiline text uses `Textarea`, numbers with steppers use `NumberField`, secrets use `PasswordField`, and a prefix, suffix or inline action that shares the input surface uses `InputGroup`.
- Put the input in a [`Field`](/components/field.md) with a `FieldLabel`. The field owns the label, `FieldDescription` and `FieldError` relationships and the `name` the value submits under.
- Use `aria-label` only when the layout has no place for a visible label, such as a search box in a toolbar. A `placeholder` shows an example value and is never the name.
- Inputs that save together belong in a real form boundary: [`Form`](/components/form.md) or a native ``, with a `Button` of `type="submit"`. Keep the submit button enabled while the form is incomplete; submitting runs validation.
- Set the native attributes that describe the value: `type`, `autoComplete`, `inputMode` and `spellCheck={false}` for URLs, emails and identifiers.
- `Input` has a single size. Use `disabled` for a value the user cannot change now, and `readOnly` for a value that can be selected and copied but not edited.
## Anatomy
```tsx
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
```
```tsx
```
## Examples
### States
Set `invalid` on the `Field` when application code owns the validity, and render `` while it is invalid; editing the URL to include `https://` clears the error. `disabled` on the `Field` disables the label and the input together. A read-only input keeps its focus ring so keyboard users can reach and copy the value.
```tsx title="states.tsx"
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'
function isValidHttpsUrl(value: string) {
try {
const url = new URL(value.trim())
return url.protocol === 'https:' && Boolean(url.hostname)
} catch {
return false
}
}
export function InputStatesDemo() {
const [repositoryUrl, setRepositoryUrl] = React.useState('github.com/langgenius')
const invalidUrl = !isValidHttpsUrl(repositoryUrl)
return (
Knowledge base name
Repository URL
{invalidUrl && Enter a full URL including https://. }
API endpoint
Workspace owner
)
}
```
### Validation in a form
Native constraints such as `required` and `type="url"` drive `FieldError`. Each `match` value names the validity state its message covers. Submit the empty form to see the messages; after a submit, they update as the value changes.
```tsx title="validation.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'
type WebhookSettingsValues = {
webhookUrl: string
notifyEmail: string
}
export function InputValidationDemo() {
const [saved, setSaved] = React.useState(false)
return (
aria-label="Webhook settings"
className="grid w-full max-w-80 gap-4"
onChange={() => {
if (saved) setSaved(false)
}}
onFormSubmit={() => setSaved(true)}
>
Webhook URL
Receives a POST request when a workflow run finishes.
Webhook URL is required.
Enter a valid URL, such as https://example.com/hooks/dify.
Notification email
Enter a valid email address.
{saved ? 'Webhook settings saved' : ''}
Save
)
}
```
### Without a visible label
A search box in a toolbar sits next to the title of the list it filters, so it has no room for a label of its own. It takes `aria-label` instead; the placeholder alone would not name it. The `` element around it marks the search landmark.
```tsx title="toolbar-search.tsx"
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'
const apps = [
{ name: 'Customer support bot', mode: 'Chatflow' },
{ name: 'Release notes writer', mode: 'Workflow' },
{ name: 'Contract reviewer', mode: 'Workflow' },
{ name: 'SQL query assistant', mode: 'Agent' },
] as const
export function InputToolbarSearchDemo() {
const [query, setQuery] = React.useState('')
const normalized = query.trim().toLowerCase()
const filtered = normalized
? apps.filter(
(app) =>
app.name.toLowerCase().includes(normalized) ||
app.mode.toLowerCase().includes(normalized),
)
: apps
return (
{filtered.length > 0 ? (
{filtered.map((app) => (
{app.name}
{app.mode}
))}
) : (
No matching apps.
)}
)
}
```
## API reference
### Input
A standalone single-line text input that integrates with `Field`. Renders an ` ` element.
Use `InputGroup` with `InputGroupInput` when the field needs a prefix, suffix, or inline action.
Inherits `className`, `render`, `style`, `onValueChange`, `defaultValue`, `value` from [Base UI Input](https://base-ui.com/react/components/input).
**Data attributes**
| Attribute | Description |
| --------------- | --------------------------------------------------------------------------- |
| `data-disabled` | Present when the input is disabled. |
| `data-valid` | Present when the input is in a valid state (when wrapped in Field.Root). |
| `data-invalid` | Present when the input is in an invalid state (when wrapped in Field.Root). |
| `data-touched` | Present when the input has been touched (when wrapped in Field.Root). |
| `data-dirty` | Present when the input's value has changed (when wrapped in Field.Root). |
| `data-filled` | Present when the input is filled (when wrapped in Field.Root). |
| `data-focused` | Present when the input is focused (when wrapped in Field.Root). |
# Input Group
> A text input that shares one surface with a prefix, suffix or action.
```tsx title="hero.tsx"
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
export function InputGroupHeroDemo() {
return (
Repository URL
https://
The https:// prefix is not part of the value.
)
}
```
## Usage guidelines
- Use `InputGroup` when one text input shares its visual surface with a prefix, suffix or action. Use the standalone [`Input`](/components/input.md) when nothing shares the surface, and do not absolutely position content over an `Input` to recreate one.
- Place the input before every addon in the DOM. The input is the primary control and addons are read or reached after it; only decorative `aria-hidden` content may come first. Set `align="inline-start"` (the default) or `align="inline-end"` on the addon for its visual position; it does not change reading or focus order.
- Give `InputGroupInput` an accessible name from a visible label, `aria-label` or `aria-labelledby`. Wrap the group in [`Field`](/components/field.md) with a `FieldLabel` for a form row; `Field` also supplies the name, validation, description and error.
- Field state reaches `InputGroupInput`, and the group derives its invalid, disabled, read-only and focus visuals from that direct input. Do not repeat those states on addons or restyle them on the group.
- Treat addon text and icons as supporting content, and mark decorative icons `aria-hidden`. Put interactive content in a `Button`, `IconButton` or link instead of adding click or keyboard handlers to the addon. Those controls keep their own focus and events.
- Pressing a non-interactive part of the group focuses the input. Pressing an interactive addon targets that control and leaves focus alone, and portalled addon content does not refocus the input. Call `preventDefault()` in the group's `onMouseDown` to opt out.
- The group supports the default input size. A new size belongs on `InputGroup`, which owns the shared surface and addon layout, rather than on the input and addons separately.
## Anatomy
```tsx
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
```
```tsx
```
`InputGroup` owns the border, background, focus ring and the non-interactive pointer surface. `InputGroupInput` owns the native input and its value. `InputGroupAddon` owns the layout of its supporting content. The direct input can also be another native input that owns its value and states, as in [`PasswordField`](/components/password-field.md).
## Examples
### Decorative icon
The search icon is decorative and renders visually first through the default `inline-start` alignment while the input stays first in the DOM. The search box filters the list it sits above and has no room for a visible label, so the input takes `aria-label`; the `` element marks it as a search landmark.
```tsx title="icon.tsx"
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import * as React from 'react'
const knowledgeBases = [
{ name: 'Product FAQ', docs: '24 docs' },
{ name: 'Refund policy', docs: '12 docs' },
{ name: 'API reference', docs: '48 docs' },
{ name: 'Release notes', docs: '19 docs' },
] as const
export function InputGroupIconDemo() {
const [query, setQuery] = React.useState('')
const normalized = query.trim().toLowerCase()
const filtered = normalized
? knowledgeBases.filter((item) => item.name.toLowerCase().includes(normalized))
: knowledgeBases
return (
{filtered.length > 0 ? (
{filtered.map((item) => (
{item.name}
{item.docs}
))}
) : (
No matching knowledge bases.
)}
)
}
```
### Suffix
`align="inline-end"` places a fixed suffix after the value. Clicking the suffix focuses the input. For numeric values with units and steppers, use [`NumberField`](/components/number-field.md) instead.
```tsx title="suffix.tsx"
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
export function InputGroupSuffixDemo() {
return (
Document file name
.md
Saved as a Markdown file in the knowledge base.
)
}
```
### Actions
Interactive addons are real controls: a text `Button` copies a read-only value, and an `IconButton` opens a `Menu` through its trigger's `render`. Neither moves focus to the input when pressed.
```tsx title="actions.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import { Menu, MenuContent, MenuItem, MenuTrigger } from '@langgenius/dify-ui/menu'
import * as React from 'react'
const endpoint = 'https://api.dify.ai/v1'
const defaultVariableName = 'summary'
export function InputGroupActionsDemo() {
const [copyCount, setCopyCount] = React.useState(0)
const [variableName, setVariableName] = React.useState(defaultVariableName)
const copied = copyCount > 0
React.useEffect(() => {
if (copyCount === 0) return
const timer = window.setTimeout(() => setCopyCount(0), 2000)
return () => window.clearTimeout(timer)
}, [copyCount])
async function handleCopy() {
try {
await navigator.clipboard.writeText(endpoint)
setCopyCount((count) => count + 1)
} catch {
// Clipboard access can be denied in insecure contexts.
}
}
return (
API endpoint
void handleCopy()}>
Copy
Copied
{copied ? 'Copied API endpoint' : ''}
Output variable
}
/>
setVariableName('context_summary')}>
Use suggested name
setVariableName(defaultVariableName)}
>
Reset to default
)
}
```
### Disabled
Setting `disabled` on `Field` disables `InputGroupInput`, and the group dims the surface and its non-interactive addons together.
```tsx title="disabled.tsx"
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
export function InputGroupDisabledDemo() {
return (
Workspace domain
.dify.app
Contact a workspace owner to change the domain.
)
}
```
### Validation
Inside a `Form`, the input's native constraints drive `FieldError`, and the whole group shows the invalid state. Errors appear when the form is submitted, then update as the value changes. Submit the form empty or with uppercase letters to see each message.
```tsx title="validation.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import * as React from 'react'
type WebAppAddressValues = {
subdomain: string
}
export function InputGroupValidationDemo() {
const [published, setPublished] = React.useState(null)
return (
aria-label="Web app address"
className="grid w-full max-w-80 gap-4"
onChange={() => {
if (published) setPublished(null)
}}
onFormSubmit={(values) => setPublished(values.subdomain)}
>
Web app address
.dify.app
Lowercase letters, numbers and hyphens.
Enter an address.
Use lowercase letters, numbers and hyphens only.
{published ? `Published at ${published}.dify.app` : ''}
Publish
)
}
```
## Keyboard
| Key | Action |
| --------------- | ----------------------------------------------------------------------------------------------------- |
| `Tab` | Moves focus to the input, then to each interactive addon in DOM order, whatever its visual alignment. |
| `Shift` + `Tab` | Moves focus back through the interactive addons and the input. |
## API reference
### InputGroup
A compound text-input container for composing an input with prefix, suffix, or action add-ons. Renders a `` element.
Place the direct `InputGroupInput` before direct `InputGroupAddon` children in the DOM and use `align` for visual placement.
Accepts the props of the element it renders.
### InputGroupAddon
**Props**
| Prop | Type | Default | Description |
| -------- | -------------------------------- | ---------------- | ----------------------------------------------------------------------------- |
| `align?` | `'inline-end' \| 'inline-start'` | `'inline-start'` | Which side of the input the add-on is shown on, independent of its DOM order. |
**Data attributes**
| Attribute | Description |
| ------------ | ----------------------------------------------- |
| `data-align` | The visual side of the input the addon sits on. |
### InputGroupInput
A native input element that automatically works with [Field](https://base-ui.com/react/components/field). Renders an `
` element.
Inherits `className`, `style`, `onValueChange`, `defaultValue`, `value` from [Base UI Input](https://base-ui.com/react/components/input).
**Data attributes**
| Attribute | Description |
| --------------- | --------------------------------------------------------------------------- |
| `data-disabled` | Present when the input is disabled. |
| `data-valid` | Present when the input is in a valid state (when wrapped in Field.Root). |
| `data-invalid` | Present when the input is in an invalid state (when wrapped in Field.Root). |
| `data-touched` | Present when the input has been touched (when wrapped in Field.Root). |
| `data-dirty` | Present when the input's value has changed (when wrapped in Field.Root). |
| `data-filled` | Present when the input is filled (when wrapped in Field.Root). |
| `data-focused` | Present when the input is focused (when wrapped in Field.Root). |
# Kbd
> Keycaps that display a keyboard shortcut next to an action.
```tsx title="hero.tsx"
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import * as React from 'react'
const shortcuts = [
{ action: 'Go to anything', keys: [{ symbol: '⌘', name: 'Command' }, { symbol: 'K' }] },
{ action: 'Save draft', keys: [{ symbol: '⌘', name: 'Command' }, { symbol: 'S' }] },
{
action: 'Publish app',
keys: [{ symbol: '⌘', name: 'Command' }, { symbol: '⇧', name: 'Shift' }, { symbol: 'P' }],
},
{ action: 'Run workflow', keys: [{ symbol: '⌥', name: 'Option' }, { symbol: 'R' }] },
]
export function KbdHeroDemo() {
return (
{shortcuts.map(({ action, keys }) => (
{action}
{keys.map(({ symbol, name }) => (
{name ? (
{symbol}
{name}
) : (
symbol
)}
))}
))}
)
}
```
## Usage guidelines
- **Show keys, not behavior**: `Kbd` only displays a key. The feature registers the shortcut and formats it for the platform, then renders one `Kbd` per key part.
- **Group a combination**: Wrap the keys of one shortcut in `KbdGroup`. Keys sit side by side without a `+` separator, and each keeps its own `
` element.
- **Keep the action's name clean**: Inside a button, menu item or other control, hide the keycaps with `aria-hidden`, so the accessible name stays the action, such as "Publish", instead of "Publish ⌘ ⇧ P". When the feature handles the shortcut, also set `aria-keyshortcuts` on the control, such as `Meta+Shift+P`. Do not declare a shortcut that nothing handles.
- **Name symbol keys in standalone text**: Screen readers announce symbols like `⌘`, `⇧` and `⌥` inconsistently or not at all. When keycaps are the content itself, such as a shortcut list, hide the symbol with `aria-hidden` and put the key name in `sr-only` text inside the same `Kbd`, so the key reads as "Command" once instead of the symbol plus the name.
- **Do not label `Kbd` or `KbdGroup`**: `` and the group's `` have no role that permits naming, so `aria-label` and `aria-labelledby` on them are not reliably announced. Put the key name in the content instead.
- **Match the surface**: `gray` is the default. Use `white` on a primary button or another dark, saturated surface. Set `disabled` when the owning control is disabled; it only dims the keycap and adds no ARIA state.
- **Hint, not entry point**: A shortcut in a tooltip is a visual hint for pointer users. The control still needs its own accessible name and a visible way to run the action.
## Anatomy
```tsx
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
```
```tsx
```
## Examples
### In a tooltip
The tooltip repeats the trigger's label and adds the keycaps. Assistive technology does not read the tooltip, so a trigger whose shortcut the feature handles sets `aria-keyshortcuts`. This example only displays the keys and binds no shortcut, so it leaves the attribute off.
```tsx title="tooltip.tsx"
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
export function KbdTooltipDemo() {
return (
}
/>
Go to anything
⌘
K
)
}
```
### In a menu
Each item shows its shortcut at the end of the row. The keycaps are `aria-hidden`, so the item is announced by its label alone. An item whose shortcut the feature handles also sets `aria-keyshortcuts`; these items only display keys.
```tsx title="menu.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from '@langgenius/dify-ui/menu'
const nodeActions = [
{ label: 'Copy', icon: 'i-ri-file-copy-line', keys: ['⌘', 'C'] },
{ label: 'Duplicate', icon: 'i-ri-stack-line', keys: ['⌘', 'D'] },
{ label: 'Run this step', icon: 'i-ri-play-line', keys: ['⇧', 'R'] },
]
export function KbdMenuDemo() {
return (
}
>
LLM node
{nodeActions.map(({ label, icon, keys }) => (
{label}
{keys.map((key) => (
{key}
))}
))}
Delete
Del
)
}
```
### In a button
Use `color="white"` on a primary button, and dim the keycaps with `disabled` together with the button.
```tsx title="button.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
export function KbdButtonDemo() {
return (
Publish
⌘
⇧
P
Publish
⌘
⇧
P
Save draft
⌘
S
)
}
```
## API reference
### Kbd
Displays a single keyboard key or key-like token. Renders a `` element.
**Props**
| Prop | Type | Default | Description |
| ----------- | ------------------- | -------- | -------------------------------------------------------------------------------- |
| `color?` | `'gray' \| 'white'` | `'gray'` | The background and text color of the key. |
| `disabled?` | `boolean` | `false` | Whether the key is dimmed, such as for a shortcut that is currently unavailable. |
**Data attributes**
| Attribute | Description |
| --------------- | -------------------------------------------------------- |
| `data-disabled` | Present when the key hint belongs to a disabled control. |
### KbdGroup
Groups multiple `Kbd` elements inline without replacing their individual `` semantics. Renders a `` element.
Accepts the props of the element it renders.
# Menu
> A button-triggered list of actions, with groups, submenus and filtering.
```tsx title="hero.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from '@langgenius/dify-ui/menu'
const actions = [
{ label: 'Edit info', icon: 'i-ri-edit-line' },
{ label: 'Duplicate', icon: 'i-ri-file-copy-line' },
{ label: 'Export DSL', icon: 'i-ri-download-2-line' },
] as const
export function MenuHeroDemo() {
return (
}
>
App actions
{actions.map((action) => (
{action.label}
))}
Delete
)
}
```
## Usage guidelines
- Use `Menu` for a list of commands that a button opens. Use `ContextMenu` for the same actions on right-click, and `Select` or `Combobox` when the user picks a value for a form or a filter.
- Open the menu with a `MenuTrigger` under its `Menu`. An icon-only trigger needs its own `aria-label`; a tooltip on it is not its name. Add the target to the name, such as "More actions for Customer support bot", when a list repeats the same trigger.
- Keep a dialog that a menu item opens as a sibling of the `Menu`, not inside `MenuContent`. The item opens it through the dialog's handle: `open(null)` when the dialog already knows its target, `openWithPayload` when the item supplies it. Do not keep an open flag in state for this.
- Use `variant="destructive"` for an item that deletes or removes, and set it apart with a `MenuSeparator`.
- Use `MenuCheckboxItem` and `MenuRadioGroup` for view settings that apply as soon as they change, such as sorting a list. Keep the selection visible with the item indicators.
- Wrap a long action list in `MenuFilterProvider` and give the `MenuInput` a name. Put the items in `MenuList`, and place the separator between groups at the start of the later `MenuGroup` so it hides with the groups that filtering removes.
## Anatomy
```tsx
import {
Menu,
MenuCheckboxItem,
MenuCheckboxItemIndicator,
MenuContent,
MenuGroup,
MenuGroupLabel,
MenuItem,
MenuLinkItem,
MenuRadioGroup,
MenuRadioItem,
MenuRadioItemIndicator,
MenuSeparator,
MenuSubmenu,
MenuSubmenuTrigger,
MenuTrigger,
} from '@langgenius/dify-ui/menu'
```
```tsx
```
A filterable menu wraps the root in `MenuFilterProvider` and fills `MenuContent` with `MenuInputGroup` (holding `MenuInput` and `MenuClear`), `MenuEmpty` and `MenuList`.
`MenuContent` bundles the portal, positioner and styled popup. Compose `MenuPortal`, `MenuPositioner` and `MenuPopup` only when the positioner needs props that `MenuContent` does not take.
## Examples
### Opening a dialog from an item
Each row has its own menu, and one `AlertDialog` serves the whole list. The Clear logs item calls `openWithPayload` on the dialog's handle with its app, and the dialog reads the payload of the session.
```tsx title="open-dialog.tsx"
import {
AlertDialog,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
createAlertDialogHandle,
} from '@langgenius/dify-ui/alert-dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from '@langgenius/dify-ui/menu'
import * as React from 'react'
type App = {
id: string
name: string
mode: string
}
const apps: App[] = [
{ id: 'support-bot', name: 'Customer support bot', mode: 'Chatflow' },
{ id: 'release-notes', name: 'Release notes writer', mode: 'Workflow' },
{ id: 'contract-review', name: 'Contract reviewer', mode: 'Workflow' },
]
export function MenuOpenDialogDemo() {
const [confirmDialog] = React.useState(() => createAlertDialogHandle())
return (
{apps.map((app) => (
}
/>
Duplicate
Export DSL
confirmDialog.openWithPayload(app)}>
Clear logs
))}
handle={confirmDialog}>
{({ payload }) => (
Clear logs for {payload?.name}?
All run logs for this app are permanently removed. This cannot be undone.
Cancel
confirmDialog.close()}>
Clear logs
)}
)
}
```
### Checkbox and radio items
Radio items choose one option of a group and checkbox items toggle a setting. Both keep the menu open after a change, and controlling their state preserves the selection when the popup unmounts on close.
```tsx title="checkbox-radio.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
Menu,
MenuCheckboxItem,
MenuCheckboxItemIndicator,
MenuContent,
MenuGroup,
MenuGroupLabel,
MenuRadioGroup,
MenuRadioItem,
MenuRadioItemIndicator,
MenuSeparator,
MenuTrigger,
} from '@langgenius/dify-ui/menu'
import * as React from 'react'
type SortOrder = 'updated' | 'created' | 'name'
export function MenuCheckboxRadioDemo() {
const [sortOrder, setSortOrder] = React.useState('updated')
const [showArchived, setShowArchived] = React.useState(false)
return (
}
>
View
Sort by
value={sortOrder} onValueChange={setSortOrder}>
value="updated">
Last edited
value="created">
Date created
value="name">
Name
Show archived apps
)
}
```
### Submenu
`MenuSubmenu` nests a second `MenuContent` behind a `MenuSubmenuTrigger`, which shows the trailing arrow.
```tsx title="submenu.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
Menu,
MenuContent,
MenuItem,
MenuSeparator,
MenuSubmenu,
MenuSubmenuTrigger,
MenuTrigger,
} from '@langgenius/dify-ui/menu'
const folders = ['Product docs', 'Support tickets', 'Release notes']
export function MenuSubmenuDemo() {
return (
}
>
Document actions
Rename
Download
Move to
{folders.map((folder) => (
{folder}
))}
Re-index
Delete
)
}
```
### Filtering a long list
The input takes focus when the menu opens. Typing filters the items and hides groups without a match, and the arrow keys move the highlight while focus stays in the input.
```tsx title="filter.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
Menu,
MenuClear,
MenuContent,
MenuEmpty,
MenuFilterProvider,
MenuGroup,
MenuGroupLabel,
MenuInput,
MenuInputGroup,
MenuItem,
MenuList,
MenuSeparator,
MenuTrigger,
} from '@langgenius/dify-ui/menu'
const blockGroups = [
{ label: 'Logic', blocks: ['If/Else', 'Iteration', 'Loop', 'Question classifier'] },
{
label: 'Transform',
blocks: ['Code', 'Template', 'Variable aggregator', 'Parameter extractor'],
},
{ label: 'Knowledge', blocks: ['Knowledge retrieval', 'Document extractor'] },
{ label: 'Output', blocks: ['Answer', 'End', 'HTTP request'] },
]
export function MenuFilterDemo() {
return (
}
>
Add block
No blocks match
{blockGroups.map((group, index) => (
{index > 0 && }
{group.label}
{group.blocks.map((block) => (
{block}
))}
))}
)
}
```
## Keyboard
| Key | Action |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `Enter`, `Space`, `ArrowDown` | Opens the menu from a focused trigger and focuses the first item. |
| `ArrowUp` | Opens the menu from a focused trigger and focuses the last item. |
| `ArrowDown`, `ArrowUp` | Moves focus between items, including disabled ones, and wraps at the ends. |
| `Home`, `End` | Focuses the first or last item. |
| Printable characters | Focuses the next item whose label starts with the typed text. In a filterable menu, they type into the input instead. |
| `Enter`, `Space` | Activates the focused item and closes the menu. Checkbox and radio items toggle and keep the menu open. |
| `Enter`, `ArrowRight` | Opens the submenu of a focused submenu trigger and focuses its first item. |
| `ArrowLeft` | Closes the submenu and returns focus to its trigger. |
| `Escape` | Closes the innermost open menu. Closing the top menu returns focus to the trigger. |
| `Tab` | Closes the menu and moves focus to the control after the trigger. |
In a right-to-left layout, `ArrowLeft` opens a submenu and `ArrowRight` closes it. In a filterable menu, focus stays in the input while `ArrowDown` and `ArrowUp` move the highlight, and `Enter` activates the highlighted item.
## API reference
### Menu
Groups all parts of a dropdown menu supporting items, submenus, checkboxes, radios, and filtering. Doesn't render its own HTML element.
Inherits `defaultOpen`, `loopFocus`, `highlightItemOnHover`, `modal`, `onOpenChange`, `onOpenChangeComplete`, `onItemHighlighted`, `open`, `orientation`, `disabled`, `closeParentOnEsc`, `actionsRef`, `triggerId`, `defaultTriggerId`, `handle`, `children` from [Base UI Menu.Root](https://base-ui.com/react/components/menu#root).
### MenuCheckboxItem
A menu item that toggles a setting on or off. Renders a `` element.
Inherits `className`, `render`, `style`, `checked`, `defaultChecked`, `onCheckedChange`, `disabled`, `label`, `id`, `closeOnClick`, `nativeButton` from [Base UI Menu.CheckboxItem](https://base-ui.com/react/components/menu#checkboxitem).
**Data attributes**
| Attribute | Description |
| ------------------ | --------------------------------------------------- |
| `data-checked` | Present when the menu checkbox item is checked. |
| `data-unchecked` | Present when the menu checkbox item is not checked. |
| `data-disabled` | Present when the menu checkbox item is disabled. |
| `data-highlighted` | Present when the menu checkbox item is highlighted. |
### MenuCheckboxItemIndicator
Indicates whether the checkbox item is ticked. Renders a `
` element.
Inherits `className`, `render`, `style`, `keepMounted` from [Base UI Menu.CheckboxItemIndicator](https://base-ui.com/react/components/menu#checkboxitemindicator).
**Data attributes**
| Attribute | Description |
| --------------------- | --------------------------------------------------- |
| `data-checked` | Present when the menu checkbox item is checked. |
| `data-unchecked` | Present when the menu checkbox item is not checked. |
| `data-disabled` | Present when the menu checkbox item is disabled. |
| `data-starting-style` | Present when the indicator begins animating in. |
| `data-ending-style` | Present when the indicator is animating out. |
### MenuClear
A button that clears the input text. Requires the menu to be wrapped in `Menu.FilterProvider`. Renders a `` element when the input has text.
Inherits `className`, `render`, `style`, `nativeButton`, `disabled` from [Base UI Menu.Clear](https://base-ui.com/react/components/menu#clear).
**Data attributes**
| Attribute | Description |
| --------------- | ------------------------------------ |
| `data-disabled` | Present when the button is disabled. |
### MenuContent
A styled menu popup bundled with a portal and positioner. Renders a `` element.
**Props**
| Prop | Type | Default | Description |
| ------------- | -------------------------- | ------- | ------------------------------------------------------------------------------------------------------- |
| `sideOffset?` | `number \| OffsetFunction` | `4` | Distance between the anchor and the popup in pixels. Also accepts a function that returns the distance. |
| `children` | `React.ReactNode` | — | The menu items, rendered inside the popup. |
Inherits `className`, `render`, `style`, `id`, `finalFocus`, `alignOffset`, `align`, `side` from [Base UI Menu.Popup](https://base-ui.com/react/components/menu#popup).
**Data attributes**
| Attribute | Description |
| --------------------- | -------------------------------------------------------------------- |
| `data-open` | Present when the menu is open. |
| `data-closed` | Present when the menu is closed. |
| `data-starting-style` | Present when the menu begins animating in. |
| `data-ending-style` | Present when the menu is animating out. |
| `data-side` | Indicates which side the popup is positioned relative to the anchor. |
| `data-align` | Indicates how the popup is aligned relative to specified side. |
| `data-instant` | Present if animations should be instant. |
**CSS variables**
| Variable | Type | Description |
| --------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------- |
| `--available-width` | `number` | The available width between the anchor and the edge of the viewport. |
| `--available-height` | `number` | The available height between the anchor and the edge of the viewport. |
| `--anchor-width` | `number` | The anchor's width. |
| `--anchor-height` | `number` | The anchor's height. |
| `--transform-origin` | `string` | The coordinates that this element is anchored to. Used for animations and transitions. |
| `--positioner-width` | `number` | The width of the menu's positioner. It is important to set `width` to this value when using CSS to animate size changes. |
| `--positioner-height` | `number` | The height of the menu's positioner. It is important to set `height` to this value when using CSS to animate size changes. |
### MenuEmpty
A message shown when the menu has no matching items. Requires the menu to be wrapped in `Menu.FilterProvider`. Renders a `
` element.
Inherits `className`, `render`, `style` from [Base UI Menu.Empty](https://base-ui.com/react/components/menu#empty).
### MenuFilterProvider
Enables filtering for the menu or submenu it wraps. Add `Menu.Input` to the popup and place its items in `Menu.List`. Wrap each searchable submenu in its own provider. Doesn't render its own HTML element.
Inherits `children`, `filter`, `autoHighlight`, `locale`, `defaultValue`, `value`, `onValueChange` from [Base UI Menu.FilterProvider](https://base-ui.com/react/components/menu#filterprovider).
### MenuGroup
Groups related menu items with the corresponding label. Renders a `
` element.
Inherits `children`, `className`, `render`, `style` from [Base UI Menu.Group](https://base-ui.com/react/components/menu#group).
### MenuGroupLabel
An accessible label that is automatically associated with its parent group. Renders a `
` element.
Inherits `className`, `render`, `style` from [Base UI Menu.GroupLabel](https://base-ui.com/react/components/menu#grouplabel).
### MenuInput
A search field that filters the menu items. Requires the menu to be wrapped in `Menu.FilterProvider`. Renders an `
` element.
Inherits `className`, `render`, `style` from [Base UI Menu.Input](https://base-ui.com/react/components/menu#input).
**Data attributes**
| Attribute | Description |
| ------------------ | -------------------------------------------------------------------------------------------------- |
| `data-highlighted` | Present while the input shows its focus ring. Cleared when keyboard navigation highlights an item. |
### MenuInputGroup
Wraps `MenuInput` and `MenuClear` on an `InputGroup` surface for filterable menus inside `MenuFilterProvider`. Renders a `
` element.
Accepts the props of the element it renders.
### MenuItem
An individual interactive item in the menu. Renders a `
` element.
**Props**
| Prop | Type | Default | Description |
| ---------- | ---------------------------- | ----------- | ------------------------------------------------- |
| `variant?` | `'default' \| 'destructive'` | `'default'` | Whether the item represents a destructive action. |
Inherits `disabled`, `label`, `id`, `closeOnClick`, `className`, `render`, `style`, `nativeButton` from [Base UI Menu.Item](https://base-ui.com/react/components/menu#item).
**Data attributes**
| Attribute | Description |
| ------------------ | -------------------------------------------- |
| `data-variant` | The item variant, set by the `variant` prop. |
| `data-highlighted` | Present when the menu item is highlighted. |
| `data-disabled` | Present when the menu item is disabled. |
### MenuLinkItem
A link in the menu that can be used to navigate to a different page or section. Renders an `
` element.
**Props**
| Prop | Type | Default | Description |
| --------------- | ---------------------------- | ----------- | --------------------------------------------------- |
| `variant?` | `'default' \| 'destructive'` | `'default'` | Whether the item represents a destructive action. |
| `closeOnClick?` | `boolean` | `true` | Whether to close the menu when the item is clicked. |
Inherits `className`, `render`, `style`, `label`, `id` from [Base UI Menu.LinkItem](https://base-ui.com/react/components/menu#linkitem).
**Data attributes**
| Attribute | Description |
| ------------------ | -------------------------------------------- |
| `data-variant` | The item variant, set by the `variant` prop. |
| `data-highlighted` | Present when the link is highlighted. |
### MenuList
Groups menu items so other content, such as a filter input, can share the popup. Renders a `` element.
Inherits `className`, `render`, `style` from [Base UI Menu.List](https://base-ui.com/react/components/menu#list).
### MenuPopup
A container for the menu items. Renders a `
` element.
Inherits `children`, `id`, `finalFocus`, `className`, `render`, `style` from [Base UI Menu.Popup](https://base-ui.com/react/components/menu#popup).
**Data attributes**
| Attribute | Description |
| --------------------- | -------------------------------------------------------------------- |
| `data-open` | Present when the menu is open. |
| `data-closed` | Present when the menu is closed. |
| `data-starting-style` | Present when the menu begins animating in. |
| `data-ending-style` | Present when the menu is animating out. |
| `data-side` | Indicates which side the popup is positioned relative to the anchor. |
| `data-align` | Indicates how the popup is aligned relative to specified side. |
| `data-instant` | Present if animations should be instant. |
### MenuPortal
A portal element that moves the popup to a different part of the DOM. By default, the portal element is appended to ``. Renders a `
` element.
Inherits `keepMounted`, `container`, `className`, `render`, `style` from [Base UI Menu.Portal](https://base-ui.com/react/components/menu#portal).
### MenuPositioner
Positions the menu popup against the trigger. Renders a `
` element.
Inherits `className`, `align`, `side`, `render`, `style`, `anchor`, `positionMethod`, `sideOffset`, `alignOffset`, `collisionBoundary`, `collisionPadding`, `sticky`, `arrowPadding`, `disableAnchorTracking`, `collisionAvoidance` from [Base UI Menu.Positioner](https://base-ui.com/react/components/menu#positioner).
**Data attributes**
| Attribute | Description |
| -------------------- | -------------------------------------------------------------------- |
| `data-open` | Present when the menu popup is open. |
| `data-closed` | Present when the menu popup is closed. |
| `data-anchor-hidden` | Present when the anchor is hidden. |
| `data-side` | Indicates which side the popup is positioned relative to the anchor. |
| `data-align` | Indicates how the popup is aligned relative to the specified side. |
**CSS variables**
| Variable | Type | Description |
| --------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------- |
| `--available-width` | `number` | The available width between the anchor and the edge of the viewport. |
| `--available-height` | `number` | The available height between the anchor and the edge of the viewport. |
| `--anchor-width` | `number` | The anchor's width. |
| `--anchor-height` | `number` | The anchor's height. |
| `--transform-origin` | `string` | The coordinates that this element is anchored to. Used for animations and transitions. |
| `--positioner-width` | `number` | The width of the menu's positioner. It is important to set `width` to this value when using CSS to animate size changes. |
| `--positioner-height` | `number` | The height of the menu's positioner. It is important to set `height` to this value when using CSS to animate size changes. |
### MenuRadioGroup
Groups related radio items. Renders a `
` element.
**Props**
| Prop | Type | Default | Description |
| ---------------- | -------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `defaultValue?` | `Value` | — | The uncontrolled value of the radio item that should be initially selected. To render a controlled radio group, use the `value` prop instead. |
| `onValueChange?` | `((value: Value, eventDetails: MenuRadioGroupChangeEventDetails) => void)` | — | Callback fired when the selected value changes. |
| `value?` | `Value` | — | The controlled value of the radio item that should be currently selected. To render an uncontrolled radio group, use the `defaultValue` prop instead. |
Inherits `className`, `render`, `style`, `children`, `disabled` from [Base UI Menu.RadioGroup](https://base-ui.com/react/components/menu#radiogroup).
**Data attributes**
| Attribute | Description |
| --------------- | ---------------------------------- |
| `data-disabled` | Whether the component is disabled. |
### MenuRadioItem
A menu item that works like a radio button in a given group. Renders a `
` element.
**Props**
| Prop | Type | Default | Description |
| ------- | ------- | ------- | ------------------------------------------------------------------------ |
| `value` | `Value` | — | The value set on the surrounding radio group when this item is selected. |
Inherits `className`, `render`, `style`, `nativeButton`, `disabled`, `label`, `id`, `closeOnClick` from [Base UI Menu.RadioItem](https://base-ui.com/react/components/menu#radioitem).
**Data attributes**
| Attribute | Description |
| ------------------ | ------------------------------------------------- |
| `data-checked` | Present when the menu radio item is selected. |
| `data-unchecked` | Present when the menu radio item is not selected. |
| `data-disabled` | Present when the menu radio item is disabled. |
| `data-highlighted` | Present when the menu radio item is highlighted. |
### MenuRadioItemIndicator
Indicates whether the radio item is selected. Renders a `
` element.
Inherits `className`, `render`, `style`, `keepMounted` from [Base UI Menu.RadioItemIndicator](https://base-ui.com/react/components/menu#radioitemindicator).
**Data attributes**
| Attribute | Description |
| --------------------- | ----------------------------------------------------- |
| `data-checked` | Present when the menu radio item is selected. |
| `data-unchecked` | Present when the menu radio item is not selected. |
| `data-disabled` | Present when the menu radio item is disabled. |
| `data-starting-style` | Present when the radio indicator begins animating in. |
| `data-ending-style` | Present when the radio indicator is animating out. |
### MenuSeparator
A separator element accessible to screen readers. Renders a `` element.
Inherits `orientation`, `className`, `render`, `style` from [Base UI Separator](https://base-ui.com/react/components/separator).
**Data attributes**
| Attribute | Description |
| ------------------ | ------------------------------------------- |
| `data-orientation` | Indicates the orientation of the separator. |
### MenuSubmenu
Groups all parts of a submenu. Doesn't render its own HTML element.
Inherits `onOpenChange`, `closeParentOnEsc`, `children`, `defaultOpen`, `loopFocus`, `highlightItemOnHover`, `onOpenChangeComplete`, `onItemHighlighted`, `open`, `orientation`, `disabled`, `actionsRef` from [Base UI Menu.SubmenuRoot](https://base-ui.com/react/components/menu#submenuroot).
### MenuSubmenuTrigger
A menu item that opens a submenu. Renders a `
` element.
**Props**
| Prop | Type | Default | Description |
| ---------- | ---------------------------- | ----------- | ------------------------------------------------- |
| `variant?` | `'default' \| 'destructive'` | `'default'` | Whether the item represents a destructive action. |
Inherits `className`, `label`, `id`, `disabled`, `delay`, `closeDelay`, `openOnHover`, `render`, `style`, `nativeButton` from [Base UI Menu.SubmenuTrigger](https://base-ui.com/react/components/menu#submenutrigger).
**Data attributes**
| Attribute | Description |
| ------------------ | ------------------------------------------------ |
| `data-variant` | The item variant, set by the `variant` prop. |
| `data-popup-open` | Present when the corresponding submenu is open. |
| `data-highlighted` | Present when the submenu trigger is highlighted. |
| `data-disabled` | Present when the submenu trigger is disabled. |
### MenuTrigger
A button that opens the menu. Renders a `
` element.
Inherits `className`, `children`, `disabled`, `handle`, `payload`, `delay`, `closeDelay`, `openOnHover`, `render`, `style`, `nativeButton` from [Base UI Menu.Trigger](https://base-ui.com/react/components/menu#trigger).
**Data attributes**
| Attribute | Description |
| ----------------- | -------------------------------------------- |
| `data-popup-open` | Present when the corresponding menu is open. |
| `data-pressed` | Present when the trigger is pressed. |
| `data-disabled` | Present when the trigger is disabled. |
### createMenuHandle
Creates a new handle to connect a Menu.Root with detached Menu.Trigger components.
```ts
createMenuHandle(): BaseMenu.Handle
```
**Returns:** `BaseMenu.Handle`
**Return properties**
| Member | Type | Description |
| -------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open` | `(triggerId: string) => void` | Opens the menu and associates it with the trigger with the given id. This method should only be called in an event handler or an effect (not during rendering). |
| `close` | `() => void` | Closes the menu. This method should only be called in an event handler or an effect (not during rendering). |
| `isOpen` | `boolean` | Whether the menu is currently open. Returns `false` while no root is attached to the handle. |
### useMenuFilter
```ts
useMenuFilter(options?: GetFilterParameters): Filter
```
**Parameters**
| Parameter | Type | Description |
| ---------- | --------------------- | ----------- |
| `options?` | `GetFilterParameters` | — |
**Returns:** `Filter`
**Return properties**
| Member | Type | Description |
| ------------ | ------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| `contains` | `- (item: Item, query: string, itemToString?: (item: Item) => string) => boolean` | Returns whether the item matches the query anywhere. |
| `startsWith` | `
- (item: Item, query: string, itemToString?: (item: Item) => string) => boolean` | Returns whether the item starts with the query. |
| `endsWith` | `
- (item: Item, query: string, itemToString?: (item: Item) => string) => boolean` | Returns whether the item ends with the query. |
# Meter
> A bar that shows a measured value within a known range.
```tsx title="hero.tsx"
import {
Meter,
MeterIndicator,
MeterLabel,
MeterTrack,
MeterValue,
} from '@langgenius/dify-ui/meter'
export function MeterHeroDemo() {
return (