Merge branch 'codex/select' into deploy/dev

This commit is contained in:
yyh 2026-04-30 14:17:28 +08:00
commit e4cf7f1c18
No known key found for this signature in database
42 changed files with 719 additions and 3320 deletions

View File

@ -202,11 +202,6 @@
"count": 1
}
},
"web/app/components/app-sidebar/dataset-info/dropdown.tsx": {
"ts/no-explicit-any": {
"count": 1
}
},
"web/app/components/app-sidebar/index.tsx": {
"ts/no-explicit-any": {
"count": 1
@ -1158,7 +1153,7 @@
},
"web/app/components/base/form/components/base/base-field.tsx": {
"no-restricted-imports": {
"count": 2
"count": 1
},
"ts/no-explicit-any": {
"count": 3
@ -1909,25 +1904,6 @@
"count": 1
}
},
"web/app/components/base/select/index.stories.tsx": {
"no-console": {
"count": 4
},
"ts/no-explicit-any": {
"count": 1
}
},
"web/app/components/base/select/index.tsx": {
"react/set-state-in-effect": {
"count": 2
},
"style/multiline-ternary": {
"count": 2
},
"ts/no-explicit-any": {
"count": 1
}
},
"web/app/components/base/sort/index.tsx": {
"ts/no-explicit-any": {
"count": 2
@ -3167,11 +3143,6 @@
"count": 2
}
},
"web/app/components/plugins/plugin-detail-panel/subscription-list/create/common-modal.tsx": {
"no-restricted-imports": {
"count": 1
}
},
"web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts": {
"erasable-syntax-only/enums": {
"count": 1
@ -5447,11 +5418,6 @@
"count": 1
}
},
"web/app/signin/_header.tsx": {
"no-restricted-imports": {
"count": 1
}
},
"web/app/signin/components/mail-and-password-auth.tsx": {
"ts/no-explicit-any": {
"count": 1

View File

@ -170,6 +170,12 @@ describe('Select wrappers', () => {
expect(screen.getByRole('combobox', { name: 'city select' }).element().querySelector('.i-ri-arrow-down-s-line')).toBeInTheDocument()
})
it('should include open state feedback classes', async () => {
const screen = await renderOpenSelect()
expect(screen.getByRole('combobox', { name: 'city select' }).element().className).toContain('data-open:bg-state-base-hover-alt')
})
})
describe('SelectContent', () => {

View File

@ -21,7 +21,7 @@ export const SelectGroup = BaseSelect.Group
const selectTriggerVariants = cva(
[
'group flex w-full items-center border-0 bg-components-input-bg-normal text-left text-components-input-text-filled outline-hidden',
'hover:bg-state-base-hover-alt focus-visible:bg-state-base-hover-alt',
'hover:bg-state-base-hover-alt focus-visible:bg-state-base-hover-alt data-open:bg-state-base-hover-alt',
'data-placeholder:text-components-input-text-placeholder',
'data-readonly:cursor-default data-readonly:bg-transparent data-readonly:hover:bg-transparent',
'data-disabled:cursor-not-allowed data-disabled:bg-components-input-bg-disabled data-disabled:text-components-input-text-filled-disabled data-disabled:hover:bg-components-input-bg-disabled',

View File

@ -113,7 +113,9 @@ vi.mock('@/service/datasets', () => ({
}))
vi.mock('@langgenius/dify-ui/toast', () => ({
toast: (...args: unknown[]) => mockToast(...args),
toast: {
error: (...args: unknown[]) => mockToast(...args),
},
}))
vi.mock('@/app/components/datasets/rename-modal', () => ({
@ -220,7 +222,7 @@ describe('Dropdown callback coverage', () => {
await user.click(screen.getByText('datasetPipeline.operations.exportPipeline'))
await waitFor(() => {
expect(mockToast).toHaveBeenCalledWith('app.exportFailed', { type: 'error' })
expect(mockToast).toHaveBeenCalledWith('app.exportFailed')
})
})
@ -257,7 +259,7 @@ describe('Dropdown callback coverage', () => {
await user.click(screen.getByText('common.operation.delete'))
await waitFor(() => {
expect(mockToast).toHaveBeenCalledWith('check failed', { type: 'error' })
expect(mockToast).toHaveBeenCalledWith('check failed')
})
expect(screen.queryByText('dataset.deleteDatasetConfirmTitle')).not.toBeInTheDocument()
})

View File

@ -34,6 +34,25 @@ type DropDownProps = {
expand: boolean
}
type JsonErrorResponse = {
json: () => Promise<{ message?: string }>
}
const isJsonErrorResponse = (error: unknown): error is JsonErrorResponse => {
return typeof error === 'object'
&& error !== null
&& 'json' in error
&& typeof error.json === 'function'
}
const getErrorMessage = async (error: unknown) => {
if (!isJsonErrorResponse(error))
return 'Unknown error'
const res = await error.json()
return res?.message || 'Unknown error'
}
const DropDown = ({
expand,
}: DropDownProps) => {
@ -78,7 +97,7 @@ const DropDown = ({
downloadBlob({ data: file, fileName: `${name}.pipeline` })
}
catch {
toast(t('exportFailed', { ns: 'app' }), { type: 'error' })
toast.error(t('exportFailed', { ns: 'app' }))
}
}, [dataset, exportPipelineConfig, t])
@ -89,9 +108,8 @@ const DropDown = ({
setConfirmMessage(isUsedByApp ? t('datasetUsedByApp', { ns: 'dataset' })! : t('deleteDatasetConfirmContent', { ns: 'dataset' })!)
setShowConfirmDelete(true)
}
catch (e: any) {
const res = await e.json()
toast(res?.message || 'Unknown error', { type: 'error' })
catch (e: unknown) {
toast.error(await getErrorMessage(e))
}
}, [dataset.id, t])
@ -112,10 +130,15 @@ const DropDown = ({
open={open}
onOpenChange={setOpen}
>
<DropdownMenuTrigger render={<div />}>
<ActionButton className={cn(expand ? 'size-8 rounded-lg' : 'size-6 rounded-md', open && 'bg-state-base-hover')}>
<span aria-hidden className="i-ri-more-fill size-4" />
</ActionButton>
<DropdownMenuTrigger
render={(
<ActionButton
aria-label={t('operation.more', { ns: 'common' })}
className={cn(expand ? 'size-8 rounded-lg' : 'size-6 rounded-md', open && 'bg-state-base-hover')}
/>
)}
>
<span aria-hidden className="i-ri-more-fill size-4" />
</DropdownMenuTrigger>
<DropdownMenuContent
placement={expand ? 'bottom-end' : 'right-start'}

View File

@ -2,6 +2,7 @@ import type { AnyFieldApi } from '@tanstack/react-form'
import type { FormSchema } from '@/app/components/base/form/types'
import { useForm } from '@tanstack/react-form'
import { act, fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FormItemValidateStatusEnum, FormTypeEnum } from '@/app/components/base/form/types'
import BaseField from '../base-field'
@ -117,6 +118,25 @@ describe('BaseField', () => {
expect(screen.queryByText('Beta')).not.toBeInTheDocument()
})
it('should not render current select value when it is filtered out by show_on conditions', () => {
renderBaseField({
formSchema: {
type: FormTypeEnum.select,
name: 'mode',
label: 'Mode',
required: false,
options: [
{ label: 'Alpha', value: 'alpha' },
{ label: 'Beta', value: 'beta', show_on: [{ variable: 'enabled', value: 'yes' }] },
],
},
defaultValues: { mode: 'beta', enabled: 'no' },
})
expect(screen.getByRole('combobox', { name: 'Mode' })).not.toHaveTextContent('beta')
expect(screen.getByRole('combobox', { name: 'Mode' })).toHaveTextContent('common.placeholder.input')
})
it('should render dynamic select loading state', () => {
mockDynamicOptions.mockReturnValue({
data: undefined,
@ -238,6 +258,7 @@ describe('BaseField', () => {
})
it('should render dynamic options and allow selecting one', async () => {
const user = userEvent.setup()
mockDynamicOptions.mockReturnValue({
data: {
options: [
@ -258,13 +279,42 @@ describe('BaseField', () => {
defaultValues: { plugin_option: '' },
})
await act(async () => {
fireEvent.click(screen.getByText('common.placeholder.input'))
await user.click(screen.getByRole('combobox', { name: 'Plugin option' }))
await user.click(screen.getByRole('option', { name: 'Option A' }))
expect(screen.getByRole('combobox', { name: 'Plugin option' })).toHaveTextContent('Option A')
})
it('should preserve multiple dynamic select values', async () => {
const user = userEvent.setup()
mockDynamicOptions.mockReturnValue({
data: {
options: [
{ label: { en_US: 'Option A', zh_Hans: '选项A' }, value: 'a' },
{ label: { en_US: 'Option B', zh_Hans: '选项B' }, value: 'b' },
],
},
isLoading: false,
error: null,
})
await act(async () => {
fireEvent.click(screen.getByText('Option A'))
renderBaseField({
formSchema: {
type: FormTypeEnum.dynamicSelect,
name: 'plugin_options',
label: 'Plugin options',
required: false,
multiple: true,
},
defaultValues: { plugin_options: ['a'] },
showCurrentValue: true,
})
expect(screen.getByText('Option A')).toBeInTheDocument()
expect(screen.getByRole('combobox', { name: 'Plugin options' })).toHaveTextContent('common.dynamicSelect.selected')
await user.click(screen.getByRole('combobox', { name: 'Plugin options' }))
await user.click(screen.getByRole('option', { name: 'Option B' }))
expect(screen.getByTestId('field-value')).toHaveTextContent('a,b')
})
it('should update boolean field when users choose false', async () => {

View File

@ -1,6 +1,15 @@
import type { AnyFieldApi } from '@tanstack/react-form'
import type { FieldState, FormSchema, TypeWithI18N } from '@/app/components/base/form/types'
import { cn } from '@langgenius/dify-ui/cn'
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectItemText,
SelectTrigger,
SelectValue,
} from '@langgenius/dify-ui/select'
import { useStore } from '@tanstack/react-form'
import {
isValidElement,
@ -14,7 +23,6 @@ import { FormItemValidateStatusEnum, FormTypeEnum } from '@/app/components/base/
import Input from '@/app/components/base/input'
import Radio from '@/app/components/base/radio'
import RadioE from '@/app/components/base/radio/ui'
import PureSelect from '@/app/components/base/select/pure'
import Tooltip from '@/app/components/base/tooltip'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import { useTriggerPluginDynamicOptions } from '@/service/use-triggers'
@ -43,6 +51,19 @@ const getTranslatedContent = ({ content, render }: {
return ''
}
type SelectOption = {
label: string
value: string
}
const getSingleSelectValue = (value: unknown, options: SelectOption[]) => {
return options.find(option => option.value === value)?.value ?? null
}
const getSingleSelectLabel = (value: unknown, options: SelectOption[], placeholder: string | undefined) => {
return options.find(option => option.value === value)?.label ?? placeholder
}
const VALIDATE_STATUS_STYLE_MAP: Record<FormItemValidateStatusEnum, { componentClassName: string, textClassName: string, infoFieldName: string }> = {
[FormItemValidateStatusEnum.Error]: {
componentClassName: 'border-components-input-border-destructive focus:border-components-input-border-destructive',
@ -121,7 +142,7 @@ const BaseField = ({
if (!results[1])
results[1] = t('placeholder.input', { ns: 'common' })
return results
}, [label, placeholder, tooltip, description, help, renderI18nObject])
}, [label, placeholder, tooltip, description, help, renderI18nObject, t])
const watchedVariables = useMemo(() => {
const variables = new Set<string>()
@ -184,6 +205,13 @@ const BaseField = ({
field.handleChange(value)
onChange?.(field.name, value)
}, [field, onChange])
const dynamicPlaceholder = isDynamicOptionsLoading
? t('dynamicSelect.loading', { ns: 'common' })
: translatedPlaceholder
const dynamicNoticeTitle = dynamicOptionsError
? t('dynamicSelect.error', { ns: 'common' })
: (!dynamicOptions.length ? t('dynamicSelect.noData', { ns: 'common' }) : null)
const dynamicNoticeClassName = dynamicOptionsError ? 'text-text-destructive-secondary' : undefined
return (
<>
@ -223,19 +251,58 @@ const BaseField = ({
)
}
{
formItemType === FormTypeEnum.select && !multiple && (
<PureSelect
value={value}
onChange={v => handleChange(v)}
disabled={disabled}
placeholder={translatedPlaceholder}
options={memorizedOptions}
triggerPopupSameWidth
popupProps={{
className: 'max-h-[320px] overflow-y-auto',
}}
/>
)
formItemType === FormTypeEnum.select && (multiple
? (
<Select
multiple
items={memorizedOptions}
value={Array.isArray(value) ? value : []}
disabled={disabled}
onValueChange={handleChange}
>
<SelectTrigger id={field.name} aria-label={translatedLabel || field.name} className="px-2">
<SelectValue placeholder={translatedPlaceholder}>
{(selectedValue: string[]) => selectedValue.length
? t('dynamicSelect.selected', { ns: 'common', count: selectedValue.length })
: translatedPlaceholder}
</SelectValue>
</SelectTrigger>
<SelectContent popupClassName="max-h-[320px] w-(--anchor-width) bg-components-panel-bg-blur">
{memorizedOptions.map(option => (
<SelectItem key={option.value} value={option.value}>
<SelectItemText>{option.label}</SelectItemText>
<SelectItemIndicator />
</SelectItem>
))}
</SelectContent>
</Select>
)
: (
<Select
items={memorizedOptions}
value={getSingleSelectValue(value, memorizedOptions)}
disabled={disabled}
onValueChange={(next) => {
if (next == null)
return
handleChange(next)
}}
>
<SelectTrigger id={field.name} aria-label={translatedLabel || field.name} className="px-2">
<SelectValue placeholder={translatedPlaceholder}>
{nextValue => getSingleSelectLabel(nextValue, memorizedOptions, translatedPlaceholder)}
</SelectValue>
</SelectTrigger>
<SelectContent popupClassName="max-h-[320px] w-(--anchor-width) bg-components-panel-bg-blur">
{memorizedOptions.map(option => (
<SelectItem key={option.value} value={option.value}>
<SelectItemText>{option.label}</SelectItemText>
<SelectItemIndicator />
</SelectItem>
))}
</SelectContent>
</Select>
))
}
{
formItemType === FormTypeEnum.checkbox /* && multiple */ && (
@ -249,24 +316,76 @@ const BaseField = ({
)
}
{
formItemType === FormTypeEnum.dynamicSelect && (
<PureSelect
options={dynamicOptions}
value={value}
onChange={field.handleChange}
disabled={disabled || isDynamicOptionsLoading}
placeholder={
isDynamicOptionsLoading
? t('dynamicSelect.loading', { ns: 'common' })
: translatedPlaceholder
}
{...(dynamicOptionsError
? { popupProps: { title: t('dynamicSelect.error', { ns: 'common' }), titleClassName: 'text-text-destructive-secondary' } }
: (!dynamicOptions.length ? { popupProps: { title: t('dynamicSelect.noData', { ns: 'common' }) } } : {}))}
triggerPopupSameWidth
multiple={multiple}
/>
)
formItemType === FormTypeEnum.dynamicSelect && (multiple
? (
<Select
multiple
items={dynamicOptions}
value={Array.isArray(value) ? value : []}
disabled={disabled || isDynamicOptionsLoading}
onValueChange={field.handleChange}
>
<SelectTrigger id={field.name} aria-label={translatedLabel || field.name} className="px-2">
<SelectValue placeholder={dynamicPlaceholder}>
{(selectedValue: string[]) => selectedValue.length
? t('dynamicSelect.selected', { ns: 'common', count: selectedValue.length })
: dynamicPlaceholder}
</SelectValue>
</SelectTrigger>
<SelectContent popupClassName="w-(--anchor-width) bg-components-panel-bg-blur">
{dynamicNoticeTitle && (
<div className={cn(
'flex h-[22px] items-center px-3 system-xs-medium-uppercase text-text-tertiary',
dynamicNoticeClassName,
)}
>
{dynamicNoticeTitle}
</div>
)}
{dynamicOptions.map(option => (
<SelectItem key={option.value} value={option.value}>
<SelectItemText>{option.label}</SelectItemText>
<SelectItemIndicator />
</SelectItem>
))}
</SelectContent>
</Select>
)
: (
<Select
items={dynamicOptions}
value={getSingleSelectValue(value, dynamicOptions)}
disabled={disabled || isDynamicOptionsLoading}
onValueChange={(next) => {
if (next == null)
return
field.handleChange(next)
}}
>
<SelectTrigger id={field.name} aria-label={translatedLabel || field.name} className="px-2">
<SelectValue placeholder={dynamicPlaceholder}>
{nextValue => getSingleSelectLabel(nextValue, dynamicOptions, dynamicPlaceholder)}
</SelectValue>
</SelectTrigger>
<SelectContent popupClassName="w-(--anchor-width) bg-components-panel-bg-blur">
{dynamicNoticeTitle && (
<div className={cn(
'flex h-[22px] items-center px-3 system-xs-medium-uppercase text-text-tertiary',
dynamicNoticeClassName,
)}
>
{dynamicNoticeTitle}
</div>
)}
{dynamicOptions.map(option => (
<SelectItem key={option.value} value={option.value}>
<SelectItemText>{option.label}</SelectItemText>
<SelectItemIndicator />
</SelectItem>
))}
</SelectContent>
</Select>
))
}
{
formItemType === FormTypeEnum.radio && (

View File

@ -1,49 +0,0 @@
import { fireEvent, render, screen } from '@testing-library/react'
import CustomSelectField from '../custom-select'
const mockField = {
name: 'custom-select-field',
state: {
value: 'small',
},
handleChange: vi.fn(),
}
vi.mock('../../..', () => ({
useFieldContext: () => mockField,
}))
describe('CustomSelectField', () => {
beforeEach(() => {
vi.clearAllMocks()
mockField.state.value = 'small'
})
it('should render select placeholder or selected value', () => {
render(
<CustomSelectField
label="Size"
options={[
{ label: 'Small', value: 'small' },
{ label: 'Large', value: 'large' },
]}
/>,
)
expect(screen.getByText('Small')).toBeInTheDocument()
})
it('should update value when users select another option', () => {
render(
<CustomSelectField
label="Size"
options={[
{ label: 'Small', value: 'small' },
{ label: 'Large', value: 'large' },
]}
/>,
)
fireEvent.click(screen.getByText('Small'))
fireEvent.click(screen.getByText('Large'))
expect(mockField.handleChange).toHaveBeenCalledWith('large')
})
})

View File

@ -1,4 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import SelectField from '../select'
const mockField = {
@ -29,10 +30,27 @@ describe('SelectField', () => {
]}
/>,
)
expect(screen.getByText('Alpha')).toBeInTheDocument()
expect(screen.getByRole('combobox', { name: 'Mode' })).toHaveTextContent('Alpha')
})
it('should update value when users select another option', () => {
it('should render the option label when selected value is an empty string', () => {
mockField.state.value = ''
render(
<SelectField
label="Mode"
options={[
{ label: 'No default selected', value: '' },
{ label: 'Alpha', value: 'alpha' },
]}
/>,
)
expect(screen.getByRole('combobox', { name: 'Mode' })).toHaveTextContent('No default selected')
})
it('should update value when users select another option', async () => {
const user = userEvent.setup()
render(
<SelectField
label="Mode"
@ -42,8 +60,8 @@ describe('SelectField', () => {
]}
/>,
)
fireEvent.click(screen.getByText('Alpha'))
fireEvent.click(screen.getByText('Beta'))
await user.click(screen.getByRole('combobox', { name: 'Mode' }))
await user.click(screen.getByRole('option', { name: 'Beta' }))
expect(mockField.handleChange).toHaveBeenCalledWith('beta')
})
})

View File

@ -1,41 +0,0 @@
import type { CustomSelectProps, Option } from '../../../select/custom'
import type { LabelProps } from '../label'
import { cn } from '@langgenius/dify-ui/cn'
import { useFieldContext } from '../..'
import CustomSelect from '../../../select/custom'
import Label from '../label'
type CustomSelectFieldProps<T extends Option> = {
label: string
labelOptions?: Omit<LabelProps, 'htmlFor' | 'label'>
options: T[]
className?: string
} & Omit<CustomSelectProps<T>, 'options' | 'value' | 'onChange'>
const CustomSelectField = <T extends Option>({
label,
labelOptions,
options,
className,
...selectProps
}: CustomSelectFieldProps<T>) => {
const field = useFieldContext<string>()
return (
<div className={cn('flex flex-col gap-y-0.5', className)}>
<Label
htmlFor={field.name}
label={label}
{...(labelOptions ?? {})}
/>
<CustomSelect<T>
value={field.state.value}
options={options}
onChange={value => field.handleChange(value)}
{...selectProps}
/>
</div>
)
}
export default CustomSelectField

View File

@ -1,4 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import InputTypeSelectField from '../index'
const mockField = {
@ -20,17 +21,20 @@ describe('InputTypeSelectField', () => {
})
it('should render label and selected option', () => {
render(<InputTypeSelectField label="Input type" supportFile={true} />)
const { container } = render(<InputTypeSelectField label="Input type" supportFile={true} />)
expect(screen.getByText('Input type')).toBeInTheDocument()
expect(screen.getByText('appDebug.variableConfig.text-input')).toBeInTheDocument()
expect(container.querySelector('[role="combobox"] span > div')).not.toBeInTheDocument()
expect(container.querySelector('[role="combobox"] > span > span')).toHaveClass('flex', 'min-w-0', 'items-center', 'gap-x-0.5')
})
it('should update value when users choose another input type', () => {
it('should update value when users choose another input type', async () => {
const user = userEvent.setup()
render(<InputTypeSelectField label="Input type" supportFile={true} />)
fireEvent.click(screen.getByText('appDebug.variableConfig.text-input'))
fireEvent.click(screen.getByText('appDebug.variableConfig.number'))
await user.click(screen.getByRole('combobox', { name: 'Input type' }))
await user.click(screen.getByRole('option', { name: /appDebug.variableConfig.number/ }))
expect(mockField.handleChange).toHaveBeenCalledWith('number')
})

View File

@ -5,7 +5,7 @@ const MockIcon = () => <svg aria-label="mock icon" />
describe('InputTypeSelect Trigger', () => {
it('should show placeholder text when no option is selected', () => {
render(<Trigger option={undefined} open={false} />)
render(<Trigger option={undefined} />)
expect(screen.getByText('common.placeholder.select')).toBeInTheDocument()
})
@ -18,11 +18,25 @@ describe('InputTypeSelect Trigger', () => {
Icon: MockIcon,
type: 'string',
}}
open={false}
/>,
)
expect(screen.getByText('Text Input')).toBeInTheDocument()
expect(screen.getByText('string')).toBeInTheDocument()
})
it('should keep selected option parts in one inline flex row', () => {
render(
<Trigger
option={{
value: 'text-input',
label: 'Text Input',
Icon: MockIcon,
type: 'string',
}}
/>,
)
expect(screen.getByText('Text Input').parentElement).toHaveClass('flex', 'min-w-0', 'items-center', 'gap-x-0.5')
})
})

View File

@ -1,10 +1,13 @@
import type { CustomSelectProps } from '../../../../select/custom'
import type { LabelProps } from '../../label'
import type { FileTypeSelectOption, InputType } from './types'
import { cn } from '@langgenius/dify-ui/cn'
import { useCallback } from 'react'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
} from '@langgenius/dify-ui/select'
import { useFieldContext } from '../../..'
import CustomSelect from '../../../../select/custom'
import Label from '../../label'
import { useInputTypeOptions } from './hooks'
import Option from './option'
@ -15,24 +18,19 @@ type InputTypeSelectFieldProps = {
labelOptions?: Omit<LabelProps, 'htmlFor' | 'label'>
supportFile: boolean
className?: string
} & Omit<CustomSelectProps<FileTypeSelectOption>, 'options' | 'value' | 'onChange' | 'CustomTrigger' | 'CustomOption'>
disabled?: boolean
}
const InputTypeSelectField = ({
label,
labelOptions,
supportFile,
className,
...customSelectProps
disabled,
}: InputTypeSelectFieldProps) => {
const field = useFieldContext<InputType>()
const inputTypeOptions = useInputTypeOptions(supportFile)
const renderTrigger = useCallback((option: FileTypeSelectOption | undefined, open: boolean) => {
return <Trigger option={option} open={open} />
}, [])
const renderOption = useCallback((option: FileTypeSelectOption) => {
return <Option option={option} />
}, [])
const selected = inputTypeOptions.find(option => option.value === field.state.value)
return (
<div className={cn('flex flex-col gap-y-0.5', className)}>
@ -41,22 +39,31 @@ const InputTypeSelectField = ({
label={label}
{...(labelOptions ?? {})}
/>
<CustomSelect<FileTypeSelectOption>
value={field.state.value}
options={inputTypeOptions}
onChange={value => field.handleChange(value as InputType)}
triggerProps={{
className: 'gap-x-0.5',
<Select
items={inputTypeOptions}
value={field.state.value ?? null}
disabled={disabled}
onValueChange={(next) => {
if (next == null)
return
field.handleChange(next as InputType)
}}
popupProps={{
className: 'w-[368px]',
wrapperClassName: 'z-9999999',
itemClassName: 'gap-x-1',
}}
CustomTrigger={renderTrigger}
CustomOption={renderOption}
{...customSelectProps}
/>
>
<SelectTrigger id={field.name} className="gap-x-0.5 px-2">
<Trigger option={selected} />
</SelectTrigger>
<SelectContent popupClassName="w-[368px] bg-components-panel-bg-blur shadow-shadow-shadow-5">
{inputTypeOptions.map((option: FileTypeSelectOption) => (
<SelectItem
key={option.value}
value={option.value}
className="gap-x-1"
>
<Option option={option} />
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)
}

View File

@ -1,43 +1,27 @@
import type { FileTypeSelectOption } from './types'
import { cn } from '@langgenius/dify-ui/cn'
import { RiArrowDownSLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import Badge from '@/app/components/base/badge'
type TriggerProps = {
option: FileTypeSelectOption | undefined
open: boolean
}
const Trigger = ({
option,
open,
}: TriggerProps) => {
const { t } = useTranslation()
if (!option)
return <span className="grow p-1">{t('placeholder.select', { ns: 'common' })}</span>
return (
<>
{option
? (
<>
<option.Icon className="h-4 w-4 shrink-0 text-text-tertiary" />
<span className="grow p-1">{option.label}</span>
<div className="pr-0.5">
<Badge text={option.type} uppercase={false} />
</div>
</>
)
: (
<span className="grow p-1">{t('placeholder.select', { ns: 'common' })}</span>
)}
<RiArrowDownSLine
className={cn(
'h-4 w-4 shrink-0 text-text-quaternary group-hover:text-text-secondary',
open && 'text-text-secondary',
)}
/>
</>
<span className="flex min-w-0 items-center gap-x-0.5">
<option.Icon className="h-4 w-4 shrink-0 text-text-tertiary" />
<span className="min-w-0 grow truncate p-1">{option.label}</span>
<span className="relative inline-flex h-5 shrink-0 items-center rounded-[5px] border border-divider-deep px-[5px] system-xs-medium leading-3 whitespace-nowrap text-text-tertiary">
{option.type}
</span>
</span>
)
}

View File

@ -1,18 +1,46 @@
import type { Option, PureSelectProps } from '../../../select/pure'
import type { LabelProps } from '../label'
import { cn } from '@langgenius/dify-ui/cn'
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectItemText,
SelectTrigger,
SelectValue,
} from '@langgenius/dify-ui/select'
import { useTranslation } from 'react-i18next'
import { useFieldContext } from '../..'
import PureSelect from '../../../select/pure'
import Label from '../label'
export type Option = {
label: string
value: string
}
const getSelectedValue = (value: string | undefined, options: Option[]) => {
return options.some(option => option.value === value) ? value : null
}
const getDisplayLabel = (value: string | null, options: Option[], placeholder: string) => {
return options.find(option => option.value === value)?.label ?? placeholder
}
type SelectFieldPopupProps = {
className?: string
title?: string
titleClassName?: string
}
type SelectFieldProps = {
label: string
labelOptions?: Omit<LabelProps, 'htmlFor' | 'label'>
options: Option[]
onChange?: (value: string) => void
className?: string
} & Omit<PureSelectProps, 'options' | 'value' | 'onChange' | 'multiple'> & {
multiple?: false
placeholder?: string
disabled?: boolean
popupProps?: SelectFieldPopupProps
}
const SelectField = ({
@ -21,9 +49,13 @@ const SelectField = ({
options,
onChange,
className,
...selectProps
placeholder,
disabled,
popupProps,
}: SelectFieldProps) => {
const { t } = useTranslation()
const field = useFieldContext<string>()
const placeholderText = placeholder || t('placeholder.select', { ns: 'common' })
return (
<div className={cn('flex flex-col gap-y-0.5', className)}>
@ -32,15 +64,41 @@ const SelectField = ({
label={label}
{...(labelOptions ?? {})}
/>
<PureSelect
value={field.state.value}
options={options}
onChange={(value) => {
field.handleChange(value)
onChange?.(value)
<Select
items={options}
value={getSelectedValue(field.state.value, options)}
disabled={disabled}
onValueChange={(next) => {
if (next == null)
return
field.handleChange(next)
onChange?.(next)
}}
{...selectProps}
/>
>
<SelectTrigger id={field.name} className="px-2">
<SelectValue placeholder={placeholderText}>
{(nextValue: string | null) => getDisplayLabel(nextValue, options, placeholderText)}
</SelectValue>
</SelectTrigger>
<SelectContent popupClassName={cn('w-(--anchor-width) bg-components-panel-bg-blur', popupProps?.className)}>
{popupProps?.title && (
<div
className={cn(
'flex h-[22px] items-center px-3 system-xs-medium-uppercase text-text-tertiary',
popupProps.titleClassName,
)}
>
{popupProps.title}
</div>
)}
{options.map(option => (
<SelectItem key={option.value} value={option.value}>
<SelectItemText>{option.label}</SelectItemText>
<SelectItemIndicator />
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)
}

View File

@ -1,4 +1,4 @@
import type { Option } from '../../../select/pure'
import type { Option } from '../../components/field/select'
import type { CustomActionsProps } from '../../components/form/actions'
import type { TransferMethod } from '@/types/app'

View File

@ -1,6 +1,5 @@
import { createFormHook, createFormHookContexts } from '@tanstack/react-form'
import CheckboxField from './components/field/checkbox'
import CustomSelectField from './components/field/custom-select'
import FileTypesField from './components/field/file-types'
import FileUploaderField from './components/field/file-uploader'
import InputTypeSelectField from './components/field/input-type-select'
@ -26,7 +25,6 @@ export const { useAppForm, withForm } = createFormHook({
NumberInputField,
CheckboxField,
SelectField,
CustomSelectField,
OptionsField,
InputTypeSelectField,
FileTypesField,

View File

@ -65,12 +65,13 @@ export function Infotip({
delay={delay}
closeDelay={closeDelay}
aria-label={ariaLabel}
render={(
<span className={cn('inline-flex h-4 w-4 shrink-0 items-center justify-center', className)}>
<span aria-hidden className={cn('i-ri-question-line h-3.5 w-3.5 text-text-quaternary hover:text-text-tertiary', iconClassName)} />
</span>
className={cn(
'inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center border-0 bg-transparent p-0 focus-visible:ring-1 focus-visible:ring-components-input-border-hover focus-visible:outline-hidden',
className,
)}
/>
>
<span aria-hidden className={cn('i-ri-question-line h-3.5 w-3.5 text-text-quaternary hover:text-text-tertiary', iconClassName)} />
</PopoverTrigger>
<PopoverContent
placement={placement}
popupClassName={cn('max-w-[300px] rounded-md px-3 py-2 system-xs-regular text-text-tertiary', popupClassName)}

View File

@ -32,7 +32,7 @@ import { cn } from '@langgenius/dify-ui/cn'
import * as React from 'react'
import { useCallback, useState } from 'react'
export type PortalToFollowElemOptions = {
type PortalToFollowElemOptions = {
/*
* top, bottom, left, right
* start, end. Default is middle

View File

@ -1,124 +0,0 @@
import type { Option } from '../custom'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import CustomSelect from '../custom'
const options: Option[] = [
{ label: 'First option', value: 'first' },
{ label: 'Second option', value: 'second' },
]
describe('CustomSelect', () => {
beforeEach(() => {
vi.clearAllMocks()
})
// Rendering behavior and value fallback.
describe('Rendering', () => {
it('should show the placeholder when value is undefined or not found', () => {
const { rerender } = render(
<CustomSelect options={options} />,
)
expect(screen.getByTitle(/select/i)).toBeInTheDocument()
rerender(
<CustomSelect options={options} value="missing" />,
)
expect(screen.getByTitle(/select/i)).toBeInTheDocument()
})
})
// User interactions for opening and selecting options.
describe('User Interactions', () => {
it('should call onChange and close the popup when an option is selected', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<CustomSelect options={options} onChange={onChange} />,
)
await user.click(screen.getByTitle(/select/i))
expect(screen.getByTitle('Second option')).toBeInTheDocument()
await user.click(screen.getByTitle('Second option'))
expect(onChange).toHaveBeenCalledWith('second')
expect(screen.queryByTitle('Second option')).not.toBeInTheDocument()
})
})
// Controlled container props behavior.
describe('Container Props', () => {
it('should delegate open-state changes through containerProps.onOpenChange', async () => {
const user = userEvent.setup()
const onOpenChange = vi.fn()
render(
<CustomSelect
options={options}
containerProps={{ open: true, onOpenChange }}
/>,
)
expect(screen.getByTitle('First option')).toBeInTheDocument()
await user.click(screen.getByTitle(/select/i))
expect(onOpenChange).toHaveBeenCalledWith(false)
})
})
// Custom rendering hooks for trigger and options.
describe('Custom Renderers', () => {
it('should render CustomTrigger and CustomOption with selected state', async () => {
const user = userEvent.setup()
render(
<CustomSelect
options={options}
value="first"
CustomTrigger={(option, open) => <div>{`${option?.label ?? 'none'}-${open ? 'open' : 'closed'}`}</div>}
CustomOption={(option, selected) => <div>{`${option.label}-${selected ? 'selected' : 'idle'}`}</div>}
/>,
)
expect(screen.getByText('First option-closed')).toBeInTheDocument()
await user.click(screen.getByText('First option-closed'))
expect(screen.getByText('First option-open')).toBeInTheDocument()
expect(screen.getByText('First option-selected')).toBeInTheDocument()
expect(screen.getByText('Second option-idle')).toBeInTheDocument()
})
})
// Class-based customization props.
describe('Style Props', () => {
it('should apply trigger and popup class names from props', async () => {
const user = userEvent.setup()
render(
<CustomSelect
options={options}
triggerProps={{ className: 'trigger-class' }}
popupProps={{
wrapperClassName: 'wrapper-class',
className: 'popup-class',
itemClassName: 'item-class',
}}
/>,
)
const triggerLabel = screen.getByTitle(/select/i)
const trigger = triggerLabel.parentElement
expect(trigger).toHaveClass('trigger-class')
await user.click(triggerLabel)
expect(document.querySelector('.wrapper-class')).toBeInTheDocument()
expect(document.querySelector('.popup-class')).toBeInTheDocument()
expect(document.querySelectorAll('.item-class')).toHaveLength(options.length)
})
})
})

View File

@ -1,957 +0,0 @@
import type { Item } from '../index'
import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Select, { PortalSelect, SimpleSelect } from '../index'
const items: Item[] = [
{ value: 'apple', name: 'Apple' },
{ value: 'banana', name: 'Banana' },
{ value: 'citrus', name: 'Citrus' },
]
describe('Select', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('Rendering', () => {
it('should show the default selected item when defaultValue matches an item', () => {
render(
<Select
items={items}
defaultValue="banana"
allowSearch={false}
onSelect={vi.fn()}
/>,
)
expect(screen.getByTitle('Banana'))!.toBeInTheDocument()
})
it('should render null selectedItem when defaultValue does not match any item', () => {
render(
<Select
items={items}
defaultValue="missing"
allowSearch={false}
onSelect={vi.fn()}
/>,
)
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
// No item title should appear for a non-matching default
expect(screen.queryByTitle('Apple')).not.toBeInTheDocument()
expect(screen.queryByTitle('Banana')).not.toBeInTheDocument()
})
it('should render with allowSearch=true (input mode)', () => {
render(
<Select
items={items}
defaultValue="apple"
allowSearch={true}
onSelect={vi.fn()}
/>,
)
expect(screen.getByRole('combobox'))!.toBeInTheDocument()
})
it('should apply custom bgClassName', () => {
render(
<Select
items={items}
defaultValue="apple"
allowSearch={false}
onSelect={vi.fn()}
bgClassName="bg-custom-color"
/>,
)
expect(screen.getByTitle('Apple'))!.toBeInTheDocument()
})
})
describe('User Interactions', () => {
it('should call onSelect when choosing an option from default select', async () => {
const user = userEvent.setup()
const onSelect = vi.fn()
render(
<Select
items={items}
defaultValue="banana"
allowSearch={false}
onSelect={onSelect}
/>,
)
await user.click(screen.getByTitle('Banana'))
await user.click(screen.getByText('Citrus'))
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({
value: 'citrus',
name: 'Citrus',
}))
})
it('should not open or select when default select is disabled', async () => {
const user = userEvent.setup()
const onSelect = vi.fn()
render(
<Select
items={items}
defaultValue="banana"
allowSearch={false}
disabled={true}
onSelect={onSelect}
/>,
)
await user.click(screen.getByTitle('Banana'))
expect(screen.queryByText('Citrus')).not.toBeInTheDocument()
expect(onSelect).not.toHaveBeenCalled()
})
it('should filter items when searching with allowSearch=true', async () => {
const user = userEvent.setup()
render(
<Select
items={items}
defaultValue="apple"
allowSearch={true}
onSelect={vi.fn()}
/>,
)
// First, click the chevron button to open the dropdown
const buttons = screen.getAllByRole('button')
await user.click(buttons[0]!)
// Now type in the search input to filter
const input = screen.getByRole('combobox')
await user.clear(input)
await user.type(input, 'ban')
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
// Citrus should be filtered away
expect(screen.queryByText('Citrus')).not.toBeInTheDocument()
})
it('should not filter or update query when disabled and allowSearch=true', async () => {
render(
<Select
items={items}
defaultValue="apple"
allowSearch={true}
disabled={true}
onSelect={vi.fn()}
/>,
)
const input = screen.getByRole('combobox') as HTMLInputElement
// we must use fireEvent because userEvent throws on disabled inputs
fireEvent.change(input, { target: { value: 'ban' } })
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
// We just want to ensure it doesn't throw and covers the !disabled branch in onChange.
// Since it's disabled, no search dropdown should appear.
expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
})
it('should not call onSelect when a disabled Combobox value changes externally', () => {
// In Headless UI, disabled elements do not fire events via React.
// To cover the defensive `if (!disabled)` branches inside the callbacks,
// we temporarily remove the disabled attribute from the DOM to force the event through.
const onSelect = vi.fn()
render(
<Select
items={items}
defaultValue="apple"
allowSearch={false}
disabled={true}
onSelect={onSelect}
/>,
)
const button = screen.getAllByRole('button')[0] as HTMLButtonElement
button.removeAttribute('disabled')
button.removeAttribute('aria-disabled')
fireEvent.click(button)
expect(onSelect).not.toHaveBeenCalled()
})
it('should not open dropdown when clicking ComboboxButton while disabled and allowSearch=false', () => {
// Covers line 128-141 where disabled check prevents open state toggle
render(
<Select
items={items}
defaultValue="apple"
allowSearch={false}
disabled={true}
onSelect={vi.fn()}
/>,
)
// The main trigger button should be disabled
const button = screen.getAllByRole('button')[0] as HTMLButtonElement
button.removeAttribute('disabled')
const chevron = screen.getAllByRole('button')[1] as HTMLButtonElement
chevron.removeAttribute('disabled')
fireEvent.click(button)
fireEvent.click(chevron)
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
// Dropdown options should not appear because the internal `if (!disabled)` guards it
expect(screen.queryByText('Banana')).not.toBeInTheDocument()
})
it('should handle missing item nicely in renderTrigger', () => {
render(
<SimpleSelect
items={items}
defaultValue="non-existent"
onSelect={vi.fn()}
renderTrigger={(selected) => {
return (
<span>
{/* eslint-disable-next-line style/jsx-one-expression-per-line */}
Custom: {selected?.name ?? 'Fallback'}
</span>
)
}}
/>,
)
expect(screen.getByText('Custom: Fallback'))!.toBeInTheDocument()
})
it('should render with custom renderOption', async () => {
const user = userEvent.setup()
render(
<Select
items={items}
defaultValue="apple"
allowSearch={false}
onSelect={vi.fn()}
renderOption={({ item, selected }) => (
<span data-testid={`custom-opt-${item.value}`}>
{item.name}
{selected ? ' ✓' : ''}
</span>
)}
/>,
)
await user.click(screen.getByTitle('Apple'))
expect(screen.getByTestId('custom-opt-apple'))!.toBeInTheDocument()
expect(screen.getByTestId('custom-opt-banana'))!.toBeInTheDocument()
})
it('should show ChevronUpIcon when open and ChevronDownIcon when closed', async () => {
const user = userEvent.setup()
render(
<Select
items={items}
defaultValue="apple"
allowSearch={false}
onSelect={vi.fn()}
/>,
)
// Initially closed — should have a chevron button
await user.click(screen.getByTitle('Apple'))
// Dropdown is now open
// Dropdown is now open
expect(screen.getByText('Banana'))!.toBeInTheDocument()
})
})
})
// ──────────────────────────────────────────────────────────────
// SimpleSelect (Listbox-based)
// ──────────────────────────────────────────────────────────────
describe('SimpleSelect', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('Rendering', () => {
it('should render i18n placeholder when no selection exists', () => {
render(
<SimpleSelect
items={items}
defaultValue="missing"
onSelect={vi.fn()}
/>,
)
expect(screen.getByText(/select/i))!.toBeInTheDocument()
})
it('should render custom placeholder when provided', () => {
render(
<SimpleSelect
items={items}
defaultValue="missing"
placeholder="Pick one"
onSelect={vi.fn()}
/>,
)
expect(screen.getByText('Pick one'))!.toBeInTheDocument()
})
it('should render selected item name when defaultValue matches', () => {
render(
<SimpleSelect
items={items}
defaultValue="banana"
onSelect={vi.fn()}
/>,
)
expect(screen.getByText('Banana'))!.toBeInTheDocument()
})
it('should render with isLoading=true showing spinner', () => {
render(
<SimpleSelect
items={items}
defaultValue="apple"
onSelect={vi.fn()}
isLoading={true}
/>,
)
// Loader icon should be rendered (RiLoader4Line has aria hidden)
// Loader icon should be rendered (RiLoader4Line has aria hidden)
expect(screen.getByText('Apple'))!.toBeInTheDocument()
})
it('should render group items as non-selectable headers', async () => {
const user = userEvent.setup()
const groupItems: Item[] = [
{ value: 'fruits-group', name: 'Fruits', isGroup: true },
{ value: 'apple', name: 'Apple' },
{ value: 'banana', name: 'Banana' },
]
render(
<SimpleSelect
items={groupItems}
defaultValue="apple"
onSelect={vi.fn()}
/>,
)
await user.click(screen.getByRole('button'))
expect(screen.getByText('Fruits'))!.toBeInTheDocument()
})
it('should not render ListboxOptions when disabled', () => {
render(
<SimpleSelect
items={items}
defaultValue="apple"
disabled={true}
onSelect={vi.fn()}
/>,
)
expect(screen.getByText('Apple'))!.toBeInTheDocument()
})
it('should not open SimpleSelect when disabled', async () => {
const user = userEvent.setup()
render(
<SimpleSelect
items={items}
defaultValue="apple"
disabled={true}
onSelect={vi.fn()}
/>,
)
const button = screen.getByRole('button')
await user.click(button)
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
// Banana should not be visible as it won't open
expect(screen.queryByText('Banana')).not.toBeInTheDocument()
})
it('should not trigger onSelect via onChange when Listbox is disabled', () => {
// Covers line 228 (!disabled check) inside Listbox onChange
const onSelect = vi.fn()
render(
<SimpleSelect
items={items}
defaultValue="apple"
disabled={true}
onSelect={onSelect}
/>,
)
const button = screen.getByRole('button') as HTMLButtonElement
button.removeAttribute('disabled')
button.removeAttribute('aria-disabled')
fireEvent.click(button)
expect(onSelect).not.toHaveBeenCalled()
})
})
describe('User Interactions', () => {
it('should call onSelect and update display when an option is chosen', async () => {
const user = userEvent.setup()
const onSelect = vi.fn()
render(
<SimpleSelect
items={items}
defaultValue="missing"
onSelect={onSelect}
/>,
)
await user.click(screen.getByRole('button'))
await user.click(screen.getByText('Apple'))
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({
value: 'apple',
name: 'Apple',
}))
expect(screen.getByText('Apple'))!.toBeInTheDocument()
})
it('should pass open state into renderTrigger', async () => {
const user = userEvent.setup()
render(
<SimpleSelect
items={items}
defaultValue="missing"
onSelect={vi.fn()}
renderTrigger={(selected, open) => (
<span>{`${selected?.name ?? 'none'}-${open ? 'open' : 'closed'}`}</span>
)}
/>,
)
expect(screen.getByText('none-closed'))!.toBeInTheDocument()
await user.click(screen.getByText('none-closed'))
expect(screen.getByText('none-open'))!.toBeInTheDocument()
})
it('should clear selection when XMark is clicked (notClearable=false)', async () => {
const user = userEvent.setup()
const onSelect = vi.fn()
render(
<SimpleSelect
items={items}
defaultValue="apple"
onSelect={onSelect}
notClearable={false}
/>,
)
// The clear button (XMarkIcon) should be visible when an item is selected
const clearBtn = screen.getByRole('button').querySelector('[aria-hidden="false"]')
expect(clearBtn)!.toBeInTheDocument()
await user.click(clearBtn!)
expect(onSelect).toHaveBeenCalledWith({ name: '', value: '' })
})
it('should not show clear button when notClearable is true', () => {
render(
<SimpleSelect
items={items}
defaultValue="apple"
onSelect={vi.fn()}
notClearable={true}
/>,
)
const clearBtn = screen.getByRole('button').querySelector('[aria-hidden="false"]')
expect(clearBtn).not.toBeInTheDocument()
})
it('should hide check marks when hideChecked is true', async () => {
const user = userEvent.setup()
render(
<SimpleSelect
items={items}
defaultValue="apple"
onSelect={vi.fn()}
hideChecked={true}
/>,
)
await user.click(screen.getByRole('button'))
// The selected item should be visible but without a check icon
expect(screen.getAllByText('Apple').length).toBeGreaterThanOrEqual(1)
})
it('should render with custom renderOption in SimpleSelect', async () => {
const user = userEvent.setup()
render(
<SimpleSelect
items={items}
defaultValue="apple"
onSelect={vi.fn()}
renderOption={({ item, selected }) => (
<span data-testid={`simple-opt-${item.value}`}>
{item.name}
{selected ? ' (selected)' : ''}
</span>
)}
/>,
)
await user.click(screen.getByRole('button'))
expect(screen.getByTestId('simple-opt-apple'))!.toBeInTheDocument()
expect(screen.getByTestId('simple-opt-banana'))!.toBeInTheDocument()
// Verify the custom render shows selected state
// Verify the custom render shows selected state
expect(screen.getByTestId('simple-opt-apple'))!.toHaveTextContent('Apple (selected)')
})
it('should call onOpenChange when the button is clicked', async () => {
const user = userEvent.setup()
const onOpenChange = vi.fn()
render(
<SimpleSelect
items={items}
defaultValue="apple"
onSelect={vi.fn()}
onOpenChange={onOpenChange}
/>,
)
await user.click(screen.getByRole('button'))
expect(onOpenChange).toHaveBeenCalled()
})
it('should handle disabled items that cannot be selected', async () => {
const user = userEvent.setup()
const onSelect = vi.fn()
const disabledItems: Item[] = [
{ value: 'apple', name: 'Apple' },
{ value: 'banana', name: 'Banana', disabled: true },
{ value: 'citrus', name: 'Citrus' },
]
render(
<SimpleSelect
items={disabledItems}
defaultValue="apple"
onSelect={onSelect}
/>,
)
await user.click(screen.getByRole('button'))
// Banana should be rendered but not selectable
// Banana should be rendered but not selectable
expect(screen.getByText('Banana'))!.toBeInTheDocument()
})
})
})
// ──────────────────────────────────────────────────────────────
// PortalSelect
// ──────────────────────────────────────────────────────────────
describe('PortalSelect', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('Rendering', () => {
it('should show placeholder when value is empty', () => {
render(
<PortalSelect
value=""
items={items}
onSelect={vi.fn()}
/>,
)
expect(screen.getByText(/select/i))!.toBeInTheDocument()
})
it('should show selected item name when value matches', () => {
render(
<PortalSelect
value="banana"
items={items}
onSelect={vi.fn()}
/>,
)
expect(screen.getByTitle('Banana'))!.toBeInTheDocument()
})
it('should render with custom placeholder', () => {
render(
<PortalSelect
value=""
items={items}
onSelect={vi.fn()}
placeholder="Choose fruit"
/>,
)
expect(screen.getByText('Choose fruit'))!.toBeInTheDocument()
})
it('should render with renderTrigger', () => {
render(
<PortalSelect
value="apple"
items={items}
onSelect={vi.fn()}
renderTrigger={item => (
<span data-testid="custom-trigger">{item?.name ?? 'None'}</span>
)}
/>,
)
expect(screen.getByTestId('custom-trigger'))!.toHaveTextContent('Apple')
})
it('should show INSTALLED badge when installedValue differs from selected value', () => {
render(
<PortalSelect
value="banana"
items={items}
onSelect={vi.fn()}
installedValue="apple"
/>,
)
expect(screen.getByTitle('Banana'))!.toBeInTheDocument()
})
it('should apply triggerClassNameFn', () => {
const triggerClassNameFn = vi.fn((open: boolean) => open ? 'trigger-open' : 'trigger-closed')
render(
<PortalSelect
value="apple"
items={items}
onSelect={vi.fn()}
triggerClassNameFn={triggerClassNameFn}
/>,
)
expect(triggerClassNameFn).toHaveBeenCalledWith(false)
})
})
describe('User Interactions', () => {
it('should call onSelect when choosing an option from portal dropdown', async () => {
const user = userEvent.setup()
const onSelect = vi.fn()
render(
<PortalSelect
value=""
items={items}
onSelect={onSelect}
/>,
)
await user.click(screen.getByText(/select/i))
await user.click(screen.getByText('Citrus'))
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({
value: 'citrus',
name: 'Citrus',
}))
})
it('should not open the portal dropdown when readonly is true', async () => {
const user = userEvent.setup()
render(
<PortalSelect
value=""
items={items}
readonly={true}
onSelect={vi.fn()}
/>,
)
await user.click(screen.getByText(/select/i))
expect(screen.queryByTitle('Citrus')).not.toBeInTheDocument()
})
it('should show check mark for selected item when hideChecked is false', async () => {
const user = userEvent.setup()
render(
<PortalSelect
value="banana"
items={items}
onSelect={vi.fn()}
/>,
)
await user.click(screen.getByTitle('Banana'))
// Banana option in the dropdown should be displayed
const allBananas = screen.getAllByText('Banana')
expect(allBananas.length).toBeGreaterThanOrEqual(1)
})
it('should hide check marks when hideChecked is true', async () => {
const user = userEvent.setup()
render(
<PortalSelect
value="banana"
items={items}
onSelect={vi.fn()}
hideChecked={true}
/>,
)
await user.click(screen.getByTitle('Banana'))
expect(screen.getAllByText('Banana').length).toBeGreaterThanOrEqual(1)
})
it('should display INSTALLED badge in dropdown for installed items', async () => {
const user = userEvent.setup()
render(
<PortalSelect
value="banana"
items={items}
onSelect={vi.fn()}
installedValue="apple"
/>,
)
await user.click(screen.getByTitle('Banana'))
// The installed badge should appear in the dropdown
// The installed badge should appear in the dropdown
expect(screen.getByText('INSTALLED'))!.toBeInTheDocument()
})
it('should render item.extra content in dropdown', async () => {
const user = userEvent.setup()
const extraItems: Item[] = [
{ value: 'apple', name: 'Apple', extra: <span data-testid="extra-apple">Extra</span> },
{ value: 'banana', name: 'Banana' },
]
render(
<PortalSelect
value=""
items={extraItems}
onSelect={vi.fn()}
/>,
)
await user.click(screen.getByText(/select/i))
expect(screen.getByTestId('extra-apple'))!.toBeInTheDocument()
})
})
})

View File

@ -1,116 +0,0 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import LocaleSigninSelect from '../locale-signin'
const localeItems = [
{ value: 'en-US', name: 'English (US)' },
{ value: 'zh-Hans', name: '简体中文' },
{ value: 'ja-JP', name: '日本語' },
]
describe('LocaleSigninSelect', () => {
beforeEach(() => {
vi.clearAllMocks()
})
// Rendering behavior for selected value and fallback state.
describe('Rendering', () => {
it('should render selected locale name when value matches an item', () => {
render(
<LocaleSigninSelect
items={localeItems}
value="en-US"
onChange={vi.fn()}
/>,
)
expect(screen.getByRole('button', { name: /english \(us\)/i })).toBeInTheDocument()
})
it('should render trigger without selected label when value is not found', () => {
render(
<LocaleSigninSelect
items={localeItems}
value="missing"
onChange={vi.fn()}
/>,
)
const trigger = screen.getByRole('button')
expect(trigger).toBeInTheDocument()
expect(trigger).not.toHaveTextContent('English (US)')
})
})
// Menu interactions and callback behavior.
describe('User Interactions', () => {
it('should call onChange with selected locale value when clicking an option', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<LocaleSigninSelect
items={localeItems}
value="en-US"
onChange={onChange}
/>,
)
await user.click(screen.getByRole('button', { name: /english \(us\)/i }))
await user.click(screen.getByRole('menuitem', { name: '日本語' }))
expect(onChange).toHaveBeenCalledWith('ja-JP')
})
it('should render all locale options when menu is opened', async () => {
const user = userEvent.setup()
render(
<LocaleSigninSelect
items={localeItems}
value="en-US"
onChange={vi.fn()}
/>,
)
await user.click(screen.getByRole('button', { name: /english \(us\)/i }))
expect(screen.getByRole('menuitem', { name: 'English (US)' })).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: '简体中文' })).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: '日本語' })).toBeInTheDocument()
})
})
// Edge behavior for missing callback and empty data.
describe('Edge Cases', () => {
it('should not throw when onChange is undefined and option is selected', async () => {
const user = userEvent.setup()
render(
<LocaleSigninSelect
items={localeItems}
value="en-US"
/>,
)
await user.click(screen.getByRole('button', { name: /english \(us\)/i }))
await user.click(screen.getByRole('menuitem', { name: '简体中文' }))
// No assertion needed — test verifies no exception is thrown during selection without onChange.
})
it('should render no options when items are empty', async () => {
const user = userEvent.setup()
render(
<LocaleSigninSelect
items={[]}
value="en-US"
onChange={vi.fn()}
/>,
)
await user.click(screen.getByRole('button'))
expect(screen.queryAllByRole('menuitem')).toHaveLength(0)
})
})
})

View File

@ -1,197 +0,0 @@
import type { Option } from '../pure'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import PureSelect from '../pure'
const options: Option[] = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Citrus', value: 'citrus' },
]
describe('PureSelect', () => {
beforeEach(() => {
vi.clearAllMocks()
})
// Rendering and placeholder behavior in single/multiple modes.
describe('Rendering', () => {
it('should render i18n placeholder when single value is empty', () => {
render(<PureSelect options={options} />)
expect(screen.getByTitle(/select/i))!.toBeInTheDocument()
})
it('should render custom placeholder when provided', () => {
render(<PureSelect options={options} placeholder="Choose value" />)
expect(screen.getByTitle('Choose value'))!.toBeInTheDocument()
})
it('should render selected option label in single mode', () => {
render(<PureSelect options={options} value="banana" />)
expect(screen.getByTitle('Banana'))!.toBeInTheDocument()
})
it('should render selected count text in multiple mode', () => {
render(<PureSelect options={options} multiple={true} value={['apple', 'banana']} />)
expect(screen.getByText(/selected/i))!.toBeInTheDocument()
})
it('should render placeholder in multiple mode when selected values are empty', () => {
render(<PureSelect options={options} multiple={true} value={[]} placeholder="Pick fruits" />)
expect(screen.getByTitle('Pick fruits'))!.toBeInTheDocument()
})
})
// Interaction behavior in single and multiple selection modes.
describe('User Interactions', () => {
it('should call onChange and close popup when selecting an option in single mode', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(<PureSelect options={options} onChange={onChange} />)
await user.click(screen.getByTitle(/select/i))
expect(screen.getByTitle('Banana'))!.toBeInTheDocument()
await user.click(screen.getByTitle('Banana'))
expect(onChange).toHaveBeenCalledWith('banana')
expect(screen.queryByTitle('Citrus')).not.toBeInTheDocument()
})
it('should append a new value in multiple mode when clicking an unselected option', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<PureSelect
options={options}
multiple={true}
value={['apple']}
onChange={onChange}
/>,
)
await user.click(screen.getByText(/common\.dynamicSelect\.selected/i))
await user.click(screen.getAllByTitle('Banana')[0]!)
expect(onChange).toHaveBeenCalledWith(['apple', 'banana'])
})
it('should remove an existing value in multiple mode when clicking a selected option', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<PureSelect
options={options}
multiple={true}
value={['apple', 'banana']}
onChange={onChange}
/>,
)
await user.click(screen.getByText(/common\.dynamicSelect\.selected/i))
await user.click(screen.getAllByTitle('Apple')[0]!)
expect(onChange).toHaveBeenCalledWith(['banana'])
})
it('should start with empty array when multiple value is undefined', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<PureSelect
options={options}
multiple={true}
onChange={onChange}
containerProps={{ open: true }}
/>,
)
await user.click(screen.getAllByTitle('Apple')[0]!)
expect(onChange).toHaveBeenCalledWith(['apple'])
})
})
// Controlled open state and disabled behavior.
describe('Container And Disabled Props', () => {
it('should call containerProps.onOpenChange when trigger is clicked in controlled mode', async () => {
const user = userEvent.setup()
const onOpenChange = vi.fn()
render(
<PureSelect
options={options}
containerProps={{ open: true, onOpenChange }}
/>,
)
expect(screen.getByTitle('Apple'))!.toBeInTheDocument()
await user.click(screen.getByTitle(/select/i))
expect(onOpenChange).toHaveBeenCalledWith(false)
})
it('should not open popup when disabled', async () => {
const user = userEvent.setup()
render(
<PureSelect
options={options}
disabled={true}
/>,
)
await user.click(screen.getByTitle(/select/i))
expect(screen.queryByTitle('Apple')).not.toBeInTheDocument()
})
it('should ignore option clicks when disabled even if popup is open', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<PureSelect
options={options}
disabled={true}
onChange={onChange}
containerProps={{ open: true }}
/>,
)
await user.click(screen.getAllByTitle('Apple')[0]!)
expect(onChange).not.toHaveBeenCalled()
})
})
// Style and popup customization props.
describe('Style Props', () => {
it('should apply trigger and popup class names and render popup title', () => {
render(
<PureSelect
options={options}
triggerProps={{ className: 'trigger-class' }}
popupProps={{
wrapperClassName: 'wrapper-class',
className: 'popup-class',
itemClassName: 'item-class',
title: 'Available options',
titleClassName: 'title-class',
}}
containerProps={{ open: true }}
/>,
)
const triggerLabel = screen.getByTitle(/select/i)
const trigger = triggerLabel.parentElement
expect(trigger)!.toHaveClass('trigger-class')
expect(document.querySelector('.wrapper-class'))!.toBeInTheDocument()
expect(document.querySelector('.popup-class'))!.toBeInTheDocument()
expect(document.querySelectorAll('.item-class')).toHaveLength(options.length)
expect(screen.getByText('Available options'))!.toHaveClass('title-class')
})
})
})

View File

@ -1,171 +0,0 @@
import type {
PortalToFollowElemOptions,
} from '@/app/components/base/portal-to-follow-elem'
import { cn } from '@langgenius/dify-ui/cn'
import {
RiArrowDownSLine,
RiCheckLine,
} from '@remixicon/react'
import {
useCallback,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
export type Option = {
label: string
value: string
}
export type CustomSelectProps<T extends Option> = {
options: T[]
value?: string
onChange?: (value: string) => void
containerProps?: PortalToFollowElemOptions & {
open?: boolean
onOpenChange?: (open: boolean) => void
}
triggerProps?: {
className?: string
}
popupProps?: {
wrapperClassName?: string
className?: string
itemClassName?: string
title?: string
}
CustomTrigger?: (option: T | undefined, open: boolean) => React.JSX.Element
CustomOption?: (option: T, selected: boolean) => React.JSX.Element
}
const CustomSelect = <T extends Option>({
options,
value,
onChange,
containerProps,
triggerProps,
popupProps,
CustomTrigger,
CustomOption,
}: CustomSelectProps<T>) => {
const { t } = useTranslation()
const {
open,
onOpenChange,
placement,
offset,
triggerPopupSameWidth = true,
} = containerProps || {}
const {
className: triggerClassName,
} = triggerProps || {}
const {
wrapperClassName: popupWrapperClassName,
className: popupClassName,
itemClassName: popupItemClassName,
} = popupProps || {}
const [localOpen, setLocalOpen] = useState(false)
const mergedOpen = open ?? localOpen
const handleOpenChange = useCallback((openValue: boolean) => {
onOpenChange?.(openValue)
setLocalOpen(openValue)
}, [onOpenChange])
const selectedOption = options.find(option => option.value === value)
const triggerText = selectedOption?.label || t('placeholder.select', { ns: 'common' })
return (
<PortalToFollowElem
placement={placement || 'bottom-start'}
offset={offset || 4}
open={mergedOpen}
onOpenChange={handleOpenChange}
triggerPopupSameWidth={triggerPopupSameWidth}
>
<PortalToFollowElemTrigger
onClick={() => handleOpenChange(!mergedOpen)}
asChild
>
<div
className={cn(
'group flex h-8 cursor-pointer items-center rounded-lg bg-components-input-bg-normal px-2 system-sm-regular text-components-input-text-filled hover:bg-state-base-hover-alt',
mergedOpen && 'bg-state-base-hover-alt',
triggerClassName,
)}
>
{CustomTrigger
? CustomTrigger(selectedOption, mergedOpen)
: (
<>
<div
className="grow"
title={triggerText}
>
{triggerText}
</div>
<RiArrowDownSLine
className={cn(
'h-4 w-4 shrink-0 text-text-quaternary group-hover:text-text-secondary',
mergedOpen && 'text-text-secondary',
)}
/>
</>
)}
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className={cn(
'z-10',
popupWrapperClassName,
)}
>
<div
className={cn(
'rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg shadow-shadow-shadow-5',
popupClassName,
)}
>
{
options.map((option) => {
const selected = value === option.value
return (
<div
key={option.value}
className={cn(
'flex h-8 cursor-pointer items-center rounded-lg px-2 system-sm-medium text-text-secondary hover:bg-state-base-hover',
popupItemClassName,
)}
title={option.label}
onClick={() => {
onChange?.(option.value)
handleOpenChange(false)
}}
>
{CustomOption
? CustomOption(option, selected)
: (
<>
<div className="mr-1 grow truncate px-1">
{option.label}
</div>
{
selected && <RiCheckLine className="h-4 w-4 shrink-0 text-text-accent" />
}
</>
)}
</div>
)
})
}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default CustomSelect

View File

@ -1,572 +0,0 @@
import type { Meta, StoryObj } from '@storybook/nextjs-vite'
import type { Item } from '.'
import { useState } from 'react'
import Select, { PortalSelect, SimpleSelect } from '.'
const meta = {
title: 'Base/Data Entry/Select',
component: SimpleSelect,
parameters: {
layout: 'centered',
docs: {
description: {
component: 'Select component with three variants: Select (with search), SimpleSelect (basic dropdown), and PortalSelect (portal-based positioning). Built on Headless UI.',
},
},
},
tags: ['autodocs'],
argTypes: {
placeholder: {
control: 'text',
description: 'Placeholder text',
},
disabled: {
control: 'boolean',
description: 'Disabled state',
},
notClearable: {
control: 'boolean',
description: 'Hide clear button',
},
hideChecked: {
control: 'boolean',
description: 'Hide check icon on selected item',
},
},
args: {
onSelect: (item) => {
console.log('Selected:', item)
},
},
} satisfies Meta<typeof SimpleSelect>
export default meta
type Story = StoryObj<typeof meta>
const fruits: Item[] = [
{ value: 'apple', name: 'Apple' },
{ value: 'banana', name: 'Banana' },
{ value: 'cherry', name: 'Cherry' },
{ value: 'date', name: 'Date' },
{ value: 'elderberry', name: 'Elderberry' },
]
const countries: Item[] = [
{ value: 'us', name: 'United States' },
{ value: 'uk', name: 'United Kingdom' },
{ value: 'ca', name: 'Canada' },
{ value: 'au', name: 'Australia' },
{ value: 'de', name: 'Germany' },
{ value: 'fr', name: 'France' },
{ value: 'jp', name: 'Japan' },
{ value: 'cn', name: 'China' },
]
// SimpleSelect Demo
const SimpleSelectDemo = (args: any) => {
const [selected, setSelected] = useState(args.defaultValue || '')
return (
<div style={{ width: '300px' }}>
<SimpleSelect
{...args}
items={fruits}
defaultValue={selected}
onSelect={(item) => {
setSelected(item.value)
console.log('Selected:', item)
}}
/>
{selected && (
<div className="mt-3 text-sm text-gray-600">
Selected:
{' '}
<span className="font-semibold">{selected}</span>
</div>
)}
</div>
)
}
// Default SimpleSelect
export const Default: Story = {
render: args => <SimpleSelectDemo {...args} />,
args: {
placeholder: 'Select a fruit...',
defaultValue: 'apple',
items: [],
},
}
// With placeholder (no selection)
export const WithPlaceholder: Story = {
render: args => <SimpleSelectDemo {...args} />,
args: {
placeholder: 'Choose an option...',
defaultValue: '',
items: [],
},
}
// Disabled state
export const Disabled: Story = {
render: args => <SimpleSelectDemo {...args} />,
args: {
placeholder: 'Select a fruit...',
defaultValue: 'banana',
disabled: true,
items: [],
},
}
// Not clearable
export const NotClearable: Story = {
render: args => <SimpleSelectDemo {...args} />,
args: {
placeholder: 'Select a fruit...',
defaultValue: 'cherry',
notClearable: true,
items: [],
},
}
// Hide checked icon
export const HideChecked: Story = {
render: args => <SimpleSelectDemo {...args} />,
args: {
placeholder: 'Select a fruit...',
defaultValue: 'apple',
hideChecked: true,
items: [],
},
}
// Select with search
const WithSearchDemo = () => {
const [selected, setSelected] = useState('us')
return (
<div style={{ width: '300px' }}>
<Select
items={countries}
defaultValue={selected}
onSelect={(item) => {
setSelected(item.value as string)
console.log('Selected:', item)
}}
allowSearch={true}
/>
<div className="mt-3 text-sm text-gray-600">
Selected:
{' '}
<span className="font-semibold">{selected}</span>
</div>
</div>
)
}
export const WithSearch: Story = {
render: () => <WithSearchDemo />,
parameters: { controls: { disable: true } },
} as unknown as Story
// PortalSelect
const PortalSelectVariantDemo = () => {
const [selected, setSelected] = useState('apple')
return (
<div style={{ width: '300px' }}>
<PortalSelect
value={selected}
items={fruits}
onSelect={(item) => {
setSelected(item.value as string)
console.log('Selected:', item)
}}
placeholder="Select a fruit..."
/>
<div className="mt-3 text-sm text-gray-600">
Selected:
{' '}
<span className="font-semibold">{selected}</span>
</div>
</div>
)
}
export const PortalSelectVariant: Story = {
render: () => <PortalSelectVariantDemo />,
parameters: { controls: { disable: true } },
} as unknown as Story
// Custom render option
const CustomRenderOptionDemo = () => {
const [selected, setSelected] = useState('us')
const countriesWithFlags = [
{ value: 'us', name: 'United States', flag: '🇺🇸' },
{ value: 'uk', name: 'United Kingdom', flag: '🇬🇧' },
{ value: 'ca', name: 'Canada', flag: '🇨🇦' },
{ value: 'au', name: 'Australia', flag: '🇦🇺' },
{ value: 'de', name: 'Germany', flag: '🇩🇪' },
]
return (
<div style={{ width: '300px' }}>
<SimpleSelect
items={countriesWithFlags}
defaultValue={selected}
onSelect={item => setSelected(item.value as string)}
renderOption={({ item, selected }) => (
<div className="flex w-full items-center justify-between">
<div className="flex items-center gap-2">
<span className="text-xl">{item.flag}</span>
<span>{item.name}</span>
</div>
{selected && <span className="text-blue-600"></span>}
</div>
)}
/>
</div>
)
}
export const CustomRenderOption: Story = {
render: () => <CustomRenderOptionDemo />,
parameters: { controls: { disable: true } },
} as unknown as Story
// Loading state
export const LoadingState: Story = {
render: () => {
return (
<div style={{ width: '300px' }}>
<SimpleSelect
items={[]}
defaultValue=""
onSelect={() => undefined}
placeholder="Loading options..."
isLoading={true}
/>
</div>
)
},
parameters: { controls: { disable: true } },
} as unknown as Story
// Real-world example - Form field
const FormFieldDemo = () => {
const [formData, setFormData] = useState({
country: 'us',
language: 'en',
timezone: 'pst',
})
const languages = [
{ value: 'en', name: 'English' },
{ value: 'es', name: 'Spanish' },
{ value: 'fr', name: 'French' },
{ value: 'de', name: 'German' },
{ value: 'zh', name: 'Chinese' },
]
const timezones = [
{ value: 'pst', name: 'Pacific Time (PST)' },
{ value: 'mst', name: 'Mountain Time (MST)' },
{ value: 'cst', name: 'Central Time (CST)' },
{ value: 'est', name: 'Eastern Time (EST)' },
]
return (
<div style={{ width: '400px' }} className="rounded-lg border border-gray-200 bg-white p-6">
<h3 className="mb-4 text-lg font-semibold">User Preferences</h3>
<div className="space-y-4">
<div>
<label className="mb-2 block text-sm font-medium text-gray-700">Country</label>
<SimpleSelect
items={countries}
defaultValue={formData.country}
onSelect={item => setFormData({ ...formData, country: item.value as string })}
/>
</div>
<div>
<label className="mb-2 block text-sm font-medium text-gray-700">Language</label>
<SimpleSelect
items={languages}
defaultValue={formData.language}
onSelect={item => setFormData({ ...formData, language: item.value as string })}
/>
</div>
<div>
<label className="mb-2 block text-sm font-medium text-gray-700">Timezone</label>
<SimpleSelect
items={timezones}
defaultValue={formData.timezone}
onSelect={item => setFormData({ ...formData, timezone: item.value as string })}
/>
</div>
</div>
<div className="mt-6 rounded-lg bg-gray-50 p-3 text-xs text-gray-700">
<div>
<strong>Country:</strong>
{' '}
{formData.country}
</div>
<div>
<strong>Language:</strong>
{' '}
{formData.language}
</div>
<div>
<strong>Timezone:</strong>
{' '}
{formData.timezone}
</div>
</div>
</div>
)
}
export const FormField: Story = {
render: () => <FormFieldDemo />,
parameters: { controls: { disable: true } },
} as unknown as Story
// Real-world example - Filter selector
const FilterSelectorDemo = () => {
const [status, setStatus] = useState('all')
const [priority, setPriority] = useState('all')
const statusOptions = [
{ value: 'all', name: 'All Status' },
{ value: 'active', name: 'Active' },
{ value: 'pending', name: 'Pending' },
{ value: 'completed', name: 'Completed' },
{ value: 'cancelled', name: 'Cancelled' },
]
const priorityOptions = [
{ value: 'all', name: 'All Priorities' },
{ value: 'high', name: 'High Priority' },
{ value: 'medium', name: 'Medium Priority' },
{ value: 'low', name: 'Low Priority' },
]
return (
<div style={{ width: '600px' }} className="rounded-lg border border-gray-200 bg-white p-6">
<h3 className="mb-4 text-lg font-semibold">Task Filters</h3>
<div className="mb-6 flex gap-4">
<div className="flex-1">
<label className="mb-2 block text-xs font-medium text-gray-600">Status</label>
<SimpleSelect
items={statusOptions}
defaultValue={status}
onSelect={item => setStatus(item.value as string)}
notClearable
/>
</div>
<div className="flex-1">
<label className="mb-2 block text-xs font-medium text-gray-600">Priority</label>
<SimpleSelect
items={priorityOptions}
defaultValue={priority}
onSelect={item => setPriority(item.value as string)}
notClearable
/>
</div>
</div>
<div className="rounded-lg bg-blue-50 p-4 text-sm">
<div className="mb-2 font-medium text-gray-700">Active Filters:</div>
<div className="flex gap-2">
<span className="rounded-sm bg-blue-200 px-2 py-1 text-xs text-blue-800">
Status:
{' '}
{status}
</span>
<span className="rounded-sm bg-blue-200 px-2 py-1 text-xs text-blue-800">
Priority:
{' '}
{priority}
</span>
</div>
</div>
</div>
)
}
export const FilterSelector: Story = {
render: () => <FilterSelectorDemo />,
parameters: { controls: { disable: true } },
} as unknown as Story
// Real-world example - Version selector with badge
const VersionSelectorDemo = () => {
const [selectedVersion, setSelectedVersion] = useState('2.1.0')
const versions = [
{ value: '3.0.0', name: 'v3.0.0 (Beta)' },
{ value: '2.1.0', name: 'v2.1.0 (Latest)' },
{ value: '2.0.5', name: 'v2.0.5' },
{ value: '2.0.4', name: 'v2.0.4' },
{ value: '1.9.8', name: 'v1.9.8' },
]
return (
<div style={{ width: '400px' }} className="rounded-lg border border-gray-200 bg-white p-6">
<h3 className="mb-4 text-lg font-semibold">Select Version</h3>
<PortalSelect
value={selectedVersion}
items={versions}
onSelect={item => setSelectedVersion(item.value as string)}
installedValue="2.0.5"
placeholder="Choose version..."
/>
<div className="mt-4 rounded-lg bg-gray-50 p-3 text-sm text-gray-700">
{selectedVersion !== '2.0.5' && (
<div className="mb-2 text-yellow-600">
Version change detected
</div>
)}
<div>
Current:
<strong>{selectedVersion}</strong>
</div>
<div className="mt-1 text-xs text-gray-500">Installed: 2.0.5</div>
</div>
</div>
)
}
export const VersionSelector: Story = {
render: () => <VersionSelectorDemo />,
parameters: { controls: { disable: true } },
} as unknown as Story
// Real-world example - Settings dropdown
const SettingsDropdownDemo = () => {
const [theme, setTheme] = useState('light')
const [fontSize, setFontSize] = useState('medium')
const themeOptions = [
{ value: 'light', name: '☀️ Light Mode' },
{ value: 'dark', name: '🌙 Dark Mode' },
{ value: 'auto', name: '🔄 Auto (System)' },
]
const fontSizeOptions = [
{ value: 'small', name: 'Small (12px)' },
{ value: 'medium', name: 'Medium (14px)' },
{ value: 'large', name: 'Large (16px)' },
{ value: 'xlarge', name: 'Extra Large (18px)' },
]
return (
<div style={{ width: '400px' }} className="rounded-lg border border-gray-200 bg-white p-6">
<h3 className="mb-4 text-lg font-semibold">Display Settings</h3>
<div className="space-y-4">
<div>
<label className="mb-2 block text-sm font-medium text-gray-700">Theme</label>
<SimpleSelect
items={themeOptions}
defaultValue={theme}
onSelect={item => setTheme(item.value as string)}
notClearable
/>
</div>
<div>
<label className="mb-2 block text-sm font-medium text-gray-700">Font Size</label>
<SimpleSelect
items={fontSizeOptions}
defaultValue={fontSize}
onSelect={item => setFontSize(item.value as string)}
notClearable
/>
</div>
</div>
</div>
)
}
export const SettingsDropdown: Story = {
render: () => <SettingsDropdownDemo />,
parameters: { controls: { disable: true } },
} as unknown as Story
// Comparison of variants
const VariantComparisonDemo = () => {
const [simple, setSimple] = useState('apple')
const [withSearch, setWithSearch] = useState('us')
const [portal, setPortal] = useState('banana')
return (
<div style={{ width: '700px' }} className="rounded-lg border border-gray-200 bg-white p-6">
<h3 className="mb-6 text-lg font-semibold">Select Variants Comparison</h3>
<div className="space-y-6">
<div>
<h4 className="mb-2 text-sm font-medium text-gray-700">SimpleSelect (Basic)</h4>
<div style={{ width: '300px' }}>
<SimpleSelect
items={fruits}
defaultValue={simple}
onSelect={item => setSimple(item.value as string)}
placeholder="Choose a fruit..."
/>
</div>
<p className="mt-2 text-xs text-gray-500">Standard dropdown without search</p>
</div>
<div>
<h4 className="mb-2 text-sm font-medium text-gray-700">Select (With Search)</h4>
<div style={{ width: '300px' }}>
<Select
items={countries}
defaultValue={withSearch}
onSelect={item => setWithSearch(item.value as string)}
allowSearch={true}
/>
</div>
<p className="mt-2 text-xs text-gray-500">Dropdown with search/filter capability</p>
</div>
<div>
<h4 className="mb-2 text-sm font-medium text-gray-700">PortalSelect (Portal-based)</h4>
<div style={{ width: '300px' }}>
<PortalSelect
value={portal}
items={fruits}
onSelect={item => setPortal(item.value as string)}
placeholder="Choose a fruit..."
/>
</div>
<p className="mt-2 text-xs text-gray-500">Portal-based positioning for better overflow handling</p>
</div>
</div>
</div>
)
}
export const VariantComparison: Story = {
render: () => <VariantComparisonDemo />,
parameters: { controls: { disable: true } },
} as unknown as Story
// Interactive playground
const PlaygroundDemo = () => {
const [selected, setSelected] = useState('apple')
return (
<div style={{ width: '350px' }}>
<SimpleSelect
items={fruits}
defaultValue={selected}
onSelect={item => setSelected(item.value as string)}
placeholder="Select an option..."
/>
</div>
)
}
export const Playground: Story = {
render: () => <PlaygroundDemo />,
parameters: { controls: { disable: true } },
} as unknown as Story

View File

@ -1,441 +0,0 @@
'use client'
/**
* @deprecated Use `@langgenius/dify-ui/select` instead.
* This component will be removed after migration is complete.
* See: https://github.com/langgenius/dify/issues/32767
*/
import type { FC } from 'react'
import { Combobox, ComboboxButton, ComboboxInput, ComboboxOption, ComboboxOptions, Listbox, ListboxButton, ListboxOption, ListboxOptions } from '@headlessui/react'
import { ChevronDownIcon, ChevronUpIcon, XMarkIcon } from '@heroicons/react/20/solid'
import { cn } from '@langgenius/dify-ui/cn'
import { RiCheckLine, RiLoader4Line } from '@remixicon/react'
import * as React from 'react'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import Badge from '../badge/index'
const defaultItems = [
{ value: 1, name: 'option1' },
{ value: 2, name: 'option2' },
{ value: 3, name: 'option3' },
{ value: 4, name: 'option4' },
{ value: 5, name: 'option5' },
{ value: 6, name: 'option6' },
{ value: 7, name: 'option7' },
]
export type Item = {
value: number | string
name: string
isGroup?: boolean
disabled?: boolean
extra?: React.ReactNode
} & Record<string, any>
type ISelectProps = {
className?: string
wrapperClassName?: string
renderTrigger?: (value: Item | null, isOpen: boolean) => React.JSX.Element | null
items?: Item[]
defaultValue?: number | string
disabled?: boolean
onSelect: (value: Item) => void
allowSearch?: boolean
bgClassName?: string
placeholder?: string
overlayClassName?: string
optionWrapClassName?: string
optionClassName?: string
hideChecked?: boolean
notClearable?: boolean
renderOption?: ({
item,
selected,
}: {
item: Item
selected: boolean
}) => React.ReactNode
isLoading?: boolean
onOpenChange?: (open: boolean) => void
}
const Select: FC<ISelectProps> = ({
className,
items = defaultItems,
defaultValue = 1,
disabled = false,
onSelect,
allowSearch = true,
bgClassName = 'bg-components-input-bg-normal',
overlayClassName,
optionClassName,
renderOption,
}) => {
const [query, setQuery] = useState('')
const [open, setOpen] = useState(false)
const [selectedItem, setSelectedItem] = useState<Item | null>(null)
// Ensure selectedItem is properly set when defaultValue or items change
useEffect(() => {
let defaultSelect = null
// Handle cases where defaultValue might be undefined, null, or empty string
defaultSelect = (defaultValue && items.find((item: Item) => item.value === defaultValue)) || null
setSelectedItem(defaultSelect)
}, [defaultValue, items])
const filteredItems: Item[]
= query === ''
? items
: items.filter((item) => {
return item.name.toLowerCase().includes(query.toLowerCase())
})
return (
<Combobox
as="div"
disabled={disabled}
value={selectedItem}
className={className}
onChange={(value) => {
if (!disabled) {
setSelectedItem(value)
setOpen(false)
onSelect(value as Item)
}
}}
>
<div className={cn('relative')}>
<div className="group text-text-secondary">
{allowSearch
? (
<ComboboxInput
className={`w-full rounded-lg border-0 ${bgClassName} py-1.5 pr-10 pl-3 shadow-sm group-hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden sm:text-sm sm:leading-6 ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}
onChange={(event) => {
if (!disabled)
setQuery(event.target.value)
}}
displayValue={(item: Item) => item?.name}
/>
)
: (
<ComboboxButton
onClick={
() => {
if (!disabled)
setOpen(!open)
}
}
className={cn(`flex h-9 w-full items-center rounded-lg border-0 ${bgClassName} py-1.5 pr-10 pl-3 shadow-sm group-hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden sm:text-sm sm:leading-6`, optionClassName)}
>
<div className="w-0 grow truncate text-left" title={selectedItem?.name}>{selectedItem?.name}</div>
</ComboboxButton>
)}
<ComboboxButton
className="absolute inset-y-0 right-0 flex items-center rounded-r-md px-2 focus:outline-hidden"
onClick={
() => {
if (!disabled)
setOpen(!open)
}
}
>
{open ? <ChevronUpIcon className="h-5 w-5" /> : <ChevronDownIcon className="h-5 w-5" />}
</ComboboxButton>
</div>
{(filteredItems.length > 0 && open) && (
<ComboboxOptions className={`absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md border-[0.5px] border-components-panel-border bg-components-panel-bg-blur px-1 py-1 text-base shadow-lg backdrop-blur-xs focus:outline-hidden sm:text-sm ${overlayClassName}`}>
{filteredItems.map((item: Item) => (
<ComboboxOption
key={item.value}
value={item}
className={({ active }: { active: boolean }) =>
cn('relative cursor-default rounded-lg py-2 pr-9 pl-3 text-text-secondary select-none hover:bg-state-base-hover', active ? 'bg-state-base-hover' : '', optionClassName)}
>
{({ /* active, */ selected }) => (
<>
{renderOption
? renderOption({ item, selected })
: (
<>
<span className={cn('block', selected && 'font-normal')}>{item.name}</span>
{selected && (
<span
className={cn('absolute inset-y-0 right-0 flex items-center pr-4 text-text-secondary')}
>
<RiCheckLine className="h-4 w-4" aria-hidden="true" />
</span>
)}
</>
)}
</>
)}
</ComboboxOption>
))}
</ComboboxOptions>
)}
</div>
</Combobox>
)
}
const SimpleSelect: FC<ISelectProps> = ({
className,
wrapperClassName = '',
renderTrigger,
items = defaultItems,
defaultValue = 1,
disabled = false,
onSelect,
onOpenChange,
placeholder,
optionWrapClassName,
optionClassName,
hideChecked,
notClearable,
renderOption,
isLoading = false,
}) => {
const { t } = useTranslation()
const localPlaceholder = placeholder || t('placeholder.select', { ns: 'common' })
const [selectedItem, setSelectedItem] = useState<Item | null>(null)
// Enhanced: Preserve user selection, only reset when necessary
useEffect(() => {
// Only reset if no current selection or current selection is invalid
const isCurrentSelectionValid = selectedItem && items.some(item => item.value === selectedItem.value)
if (!isCurrentSelectionValid) {
let defaultSelect = null
// Handle cases where defaultValue might be undefined, null, or empty string
defaultSelect = items.find((item: Item) => item.value === defaultValue) ?? null
setSelectedItem(defaultSelect)
}
}, [defaultValue, items, selectedItem])
const listboxRef = useRef<HTMLDivElement>(null)
return (
<Listbox
ref={listboxRef}
value={selectedItem}
onChange={(value) => {
if (!disabled) {
setSelectedItem(value)
onSelect(value as Item)
}
}}
>
{({ open }) => (
<div className={cn('group/simple-select relative h-9', wrapperClassName)}>
{renderTrigger && <ListboxButton className="w-full">{renderTrigger(selectedItem, open)}</ListboxButton>}
{!renderTrigger && (
<ListboxButton
onClick={() => {
onOpenChange?.(open)
}}
className={cn(`flex h-full w-full items-center rounded-lg border-0 bg-components-input-bg-normal pr-10 pl-3 group-hover/simple-select:bg-state-base-hover-alt focus-visible:bg-state-base-hover-alt focus-visible:outline-hidden sm:text-sm sm:leading-6 ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`, className)}
>
<span className={cn('block truncate text-left system-sm-regular text-components-input-text-filled', !selectedItem?.name && 'text-components-input-text-placeholder')}>{selectedItem?.name ?? localPlaceholder}</span>
<span className="absolute inset-y-0 right-0 flex items-center pr-2">
{isLoading
? <RiLoader4Line className="h-3.5 w-3.5 animate-spin text-text-secondary" />
: (selectedItem && !notClearable)
? (
<XMarkIcon
onClick={(e) => {
e.stopPropagation()
setSelectedItem(null)
onSelect({ name: '', value: '' })
}}
className="h-4 w-4 cursor-pointer text-text-quaternary"
aria-hidden="false"
/>
)
: (
open
? (
<ChevronUpIcon
className="h-4 w-4 text-text-quaternary group-hover/simple-select:text-text-secondary"
aria-hidden="true"
/>
)
: (
<ChevronDownIcon
className="h-4 w-4 text-text-quaternary group-hover/simple-select:text-text-secondary"
aria-hidden="true"
/>
)
)}
</span>
</ListboxButton>
)}
{(!disabled) && (
<ListboxOptions className={cn('absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur px-1 py-1 text-base shadow-lg backdrop-blur-xs focus:outline-hidden sm:text-sm', optionWrapClassName)}>
{items.map((item: Item) =>
item.isGroup ? (
<div
key={item.value}
className="px-3 py-1.5 text-xs font-medium tracking-wide text-text-tertiary uppercase select-none"
>
{item.name}
</div>
) : (
<ListboxOption
key={item.value}
className={
cn('relative cursor-pointer rounded-lg py-2 pr-9 pl-3 text-text-secondary select-none hover:bg-state-base-hover', optionClassName)
}
value={item}
disabled={item.disabled || disabled}
>
{({ /* active, */ selected }) => (
<>
{renderOption
? renderOption({ item, selected })
: (
<>
<span className={cn('block', selected && 'font-normal')}>{item.name}</span>
{selected && !hideChecked && (
<span
className={cn('absolute inset-y-0 right-0 flex items-center pr-2 text-text-accent')}
>
<RiCheckLine className="h-4 w-4" aria-hidden="true" />
</span>
)}
</>
)}
</>
)}
</ListboxOption>
),
)}
</ListboxOptions>
)}
</div>
)}
</Listbox>
)
}
type PortalSelectProps = {
value: string | number
onSelect: (value: Item) => void
items: Item[]
placeholder?: string
installedValue?: string | number
renderTrigger?: (value?: Item) => React.JSX.Element | null
triggerClassName?: string
triggerClassNameFn?: (open: boolean) => string
popupClassName?: string
popupInnerClassName?: string
readonly?: boolean
hideChecked?: boolean
}
const PortalSelect: FC<PortalSelectProps> = ({
value,
onSelect,
items,
placeholder,
installedValue,
renderTrigger,
triggerClassName,
triggerClassNameFn,
popupClassName,
popupInnerClassName,
readonly,
hideChecked,
}) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const localPlaceholder = placeholder || t('placeholder.select', { ns: 'common' })
const selectedItem = value ? items.find(item => item.value === value) : undefined
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement="bottom-start"
offset={4}
triggerPopupSameWidth={true}
>
<PortalToFollowElemTrigger onClick={() => !readonly && setOpen(v => !v)} className="w-full">
{renderTrigger
? renderTrigger(selectedItem)
: (
<div
className={cn(`
group flex h-9 items-center justify-between rounded-lg border-0 bg-components-input-bg-normal px-2.5 text-sm hover:bg-state-base-hover-alt ${readonly ? 'cursor-not-allowed' : 'cursor-pointer'}
`, triggerClassName, triggerClassNameFn?.(open))}
title={selectedItem?.name}
>
<span
className={`
grow truncate text-text-secondary
${!selectedItem?.name && 'text-components-input-text-placeholder'}
`}
>
{selectedItem?.name ?? localPlaceholder}
</span>
<div className="mx-0.5">
{!!(installedValue && selectedItem && selectedItem.value !== installedValue) && (
<Badge>
{installedValue}
{' '}
{'->'}
{' '}
{selectedItem.value}
{' '}
</Badge>
)}
</div>
<ChevronDownIcon className="h-4 w-4 shrink-0 text-text-quaternary group-hover:text-text-secondary" />
</div>
)}
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className={`z-20 ${popupClassName}`}>
<div
className={cn('max-h-60 overflow-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg px-1 py-1 text-base shadow-lg focus:outline-hidden sm:text-sm', popupInnerClassName)}
>
{items.map((item: Item) => (
<div
key={item.value}
className={`
flex h-9 cursor-pointer items-center justify-between rounded-lg px-2.5 text-text-secondary hover:bg-state-base-hover
${item.value === value && 'bg-state-base-hover'}
`}
title={item.name}
onClick={() => {
onSelect(item)
setOpen(false)
}}
>
<span
className="w-0 grow truncate"
title={item.name}
>
<span className="truncate">{item.name}</span>
{item.value === installedValue && (
<Badge uppercase={true} className="ml-1 shrink-0">INSTALLED</Badge>
)}
</span>
{!hideChecked && item.value === value && (
<RiCheckLine className="h-4 w-4 shrink-0 text-text-accent" />
)}
{item.extra}
</div>
))}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export { PortalSelect, SimpleSelect }
export default React.memo(Select)

View File

@ -1,64 +0,0 @@
'use client'
import { Menu, MenuButton, MenuItem, MenuItems, Transition } from '@headlessui/react'
import { GlobeAltIcon } from '@heroicons/react/24/outline'
import { Fragment } from 'react'
type ISelectProps = {
items: Array<{ value: string, name: string }>
value?: string
className?: string
onChange?: (value: string) => void
}
export default function LocaleSigninSelect({
items,
value,
onChange,
}: ISelectProps) {
const item = items.filter(item => item.value === value)[0]
return (
<div className="w-56 text-right">
<Menu as="div" className="relative inline-block text-left">
<div>
<MenuButton className="h-[44px]justify-center inline-flex w-full items-center rounded-lg border border-components-button-secondary-border px-[10px] py-[6px] text-[13px] font-medium text-text-primary hover:bg-state-base-hover">
<GlobeAltIcon className="mr-1 h-5 w-5" aria-hidden="true" />
{item?.name}
</MenuButton>
</div>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<MenuItems className="absolute right-0 z-10 mt-2 w-[200px] origin-top-right divide-y divide-divider-regular rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg focus:outline-hidden">
<div className="max-h-96 overflow-y-auto px-1 py-1 mask-[linear-gradient(to_bottom,transparent_0px,black_8px,black_calc(100%-8px),transparent_100%)]">
{items.map((item) => {
return (
<MenuItem key={item.value}>
<button
type="button"
className="group flex w-full items-center rounded-lg px-3 py-2 text-sm text-text-secondary data-active:bg-state-base-hover"
onClick={(evt) => {
evt.preventDefault()
onChange?.(item.value)
}}
>
{item.name}
</button>
</MenuItem>
)
})}
</div>
</MenuItems>
</Transition>
</Menu>
</div>
)
}

View File

@ -1,64 +0,0 @@
'use client'
import { Menu, MenuButton, MenuItem, MenuItems, Transition } from '@headlessui/react'
import { GlobeAltIcon } from '@heroicons/react/24/outline'
import { Fragment } from 'react'
type ISelectProps = {
items: Array<{ value: string, name: string }>
value?: string
className?: string
onChange?: (value: string) => void
}
export default function Select({
items,
value,
onChange,
}: ISelectProps) {
const item = items.filter(item => item.value === value)[0]
return (
<div className="w-56 text-right">
<Menu as="div" className="relative inline-block text-left">
<div>
<MenuButton className="h-[44px]justify-center inline-flex w-full items-center rounded-lg border border-components-button-secondary-border px-[10px] py-[6px] text-[13px] font-medium text-text-primary hover:bg-state-base-hover">
<GlobeAltIcon className="mr-1 h-5 w-5" aria-hidden="true" />
{item?.name}
</MenuButton>
</div>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<MenuItems className="absolute right-0 z-10 mt-2 w-[200px] origin-top-right divide-y divide-divider-regular rounded-md bg-components-panel-bg shadow-lg ring-1 ring-black/5 focus:outline-hidden">
<div className="px-1 py-1">
{items.map((item) => {
return (
<MenuItem key={item.value}>
<button
type="button"
className="group flex w-full items-center rounded-lg px-3 py-2 text-sm text-text-secondary data-active:bg-state-base-hover"
onClick={(evt) => {
evt.preventDefault()
onChange?.(item.value)
}}
>
{item.name}
</button>
</MenuItem>
)
})}
</div>
</MenuItems>
</Transition>
</Menu>
</div>
)
}

View File

@ -1,207 +0,0 @@
import type {
PortalToFollowElemOptions,
} from '@/app/components/base/portal-to-follow-elem'
import { cn } from '@langgenius/dify-ui/cn'
import {
RiArrowDownSLine,
RiCheckLine,
} from '@remixicon/react'
import {
useCallback,
useMemo,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
export type Option = {
label: string
value: string
}
type SharedPureSelectProps = {
options: Option[]
containerProps?: PortalToFollowElemOptions & {
open?: boolean
onOpenChange?: (open: boolean) => void
}
triggerProps?: {
className?: string
}
popupProps?: {
wrapperClassName?: string
className?: string
itemClassName?: string
title?: string
titleClassName?: string
}
placeholder?: string
disabled?: boolean
triggerPopupSameWidth?: boolean
}
type SingleSelectProps = {
multiple?: false
value?: string
onChange?: (value: string) => void
}
type MultiSelectProps = {
multiple: true
value?: string[]
onChange?: (value: string[]) => void
}
export type PureSelectProps = SharedPureSelectProps & (SingleSelectProps | MultiSelectProps)
const PureSelect = (props: PureSelectProps) => {
const {
options,
containerProps,
triggerProps,
popupProps,
placeholder,
disabled,
triggerPopupSameWidth,
multiple,
value,
onChange,
} = props
const { t } = useTranslation()
const {
open,
onOpenChange,
placement,
offset,
} = containerProps || {}
const {
className: triggerClassName,
} = triggerProps || {}
const {
wrapperClassName: popupWrapperClassName,
className: popupClassName,
itemClassName: popupItemClassName,
title: popupTitle,
titleClassName: popupTitleClassName,
} = popupProps || {}
const [localOpen, setLocalOpen] = useState(false)
const mergedOpen = open ?? localOpen
const handleOpenChange = useCallback((openValue: boolean) => {
onOpenChange?.(openValue)
setLocalOpen(openValue)
}, [onOpenChange])
const triggerText = useMemo(() => {
const placeholderText = placeholder || t('placeholder.select', { ns: 'common' })
if (multiple)
return value?.length ? t('dynamicSelect.selected', { ns: 'common', count: value.length }) : placeholderText
return options.find(option => option.value === value)?.label || placeholderText
}, [multiple, value, options, placeholder])
return (
<PortalToFollowElem
placement={placement || 'bottom-start'}
offset={offset || 4}
open={mergedOpen}
onOpenChange={handleOpenChange}
triggerPopupSameWidth={triggerPopupSameWidth}
>
<PortalToFollowElemTrigger
onClick={() => !disabled && handleOpenChange(!mergedOpen)}
asChild
>
<div
className={cn(
'group flex h-8 items-center rounded-lg bg-components-input-bg-normal px-2 system-sm-regular text-components-input-text-filled',
!disabled && 'cursor-pointer hover:bg-state-base-hover-alt',
disabled && 'cursor-not-allowed opacity-50',
mergedOpen && !disabled && 'bg-state-base-hover-alt',
triggerClassName,
)}
>
<div
className="grow"
title={triggerText}
>
{triggerText}
</div>
<RiArrowDownSLine
className={cn(
'h-4 w-4 shrink-0 text-text-quaternary group-hover:text-text-secondary',
mergedOpen && 'text-text-secondary',
)}
/>
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className={cn(
'z-9999',
popupWrapperClassName,
)}
>
<div
className={cn(
'max-h-80 overflow-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg',
popupClassName,
)}
>
{
popupTitle && (
<div className={cn(
'flex h-[22px] items-center px-3 system-xs-medium-uppercase text-text-tertiary',
popupTitleClassName,
)}
>
{popupTitle}
</div>
)
}
{
options.map(option => (
<div
key={option.value}
className={cn(
'flex h-8 cursor-pointer items-center rounded-lg px-2 system-sm-medium text-text-secondary hover:bg-state-base-hover',
popupItemClassName,
)}
title={option.label}
onClick={() => {
if (disabled)
return
if (multiple) {
const currentValues = value ?? []
const nextValues = currentValues.includes(option.value)
? currentValues.filter(valueItem => valueItem !== option.value)
: [...currentValues, option.value]
onChange?.(nextValues)
return
}
onChange?.(option.value)
handleOpenChange(false)
}}
>
<div className="mr-1 grow truncate px-1">
{option.label}
</div>
{
(
multiple
? (value ?? []).includes(option.value)
: value === option.value
) && <RiCheckLine className="h-4 w-4 shrink-0 text-text-accent" />
}
</div>
))
}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default PureSelect

View File

@ -4,6 +4,8 @@ import UsagePrioritySection from '../usage-priority-section'
describe('UsagePrioritySection', () => {
const onSelect = vi.fn()
const getAiCreditsButton = () => screen.getByRole('button', { name: /aiCreditsOption/ })
const getApiKeyButton = () => screen.getByRole('button', { name: /apiKeyOption/ })
beforeEach(() => {
vi.clearAllMocks()
@ -15,7 +17,8 @@ describe('UsagePrioritySection', () => {
render(<UsagePrioritySection value="credits" onSelect={onSelect} />)
expect(screen.getByText(/usagePriority/))!.toBeInTheDocument()
expect(screen.getAllByRole('button')).toHaveLength(2)
expect(getAiCreditsButton()).toBeInTheDocument()
expect(getApiKeyButton()).toBeInTheDocument()
})
})
@ -24,24 +27,21 @@ describe('UsagePrioritySection', () => {
it('should highlight AI credits option when value is credits', () => {
render(<UsagePrioritySection value="credits" onSelect={onSelect} />)
const buttons = screen.getAllByRole('button')
expect(buttons[0]!.className).toContain('border-components-option-card-option-selected-border')
expect(buttons[1]!.className).not.toContain('border-components-option-card-option-selected-border')
expect(getAiCreditsButton()).toHaveAttribute('aria-pressed', 'true')
expect(getApiKeyButton()).toHaveAttribute('aria-pressed', 'false')
})
it('should highlight API key option when value is apiKey', () => {
render(<UsagePrioritySection value="apiKey" onSelect={onSelect} />)
const buttons = screen.getAllByRole('button')
expect(buttons[0]!.className).not.toContain('border-components-option-card-option-selected-border')
expect(buttons[1]!.className).toContain('border-components-option-card-option-selected-border')
expect(getAiCreditsButton()).toHaveAttribute('aria-pressed', 'false')
expect(getApiKeyButton()).toHaveAttribute('aria-pressed', 'true')
})
it('should highlight API key option when value is apiKeyOnly', () => {
render(<UsagePrioritySection value="apiKeyOnly" onSelect={onSelect} />)
const buttons = screen.getAllByRole('button')
expect(buttons[1]!.className).toContain('border-components-option-card-option-selected-border')
expect(getApiKeyButton()).toHaveAttribute('aria-pressed', 'true')
})
})
@ -50,7 +50,7 @@ describe('UsagePrioritySection', () => {
it('should call onSelect with system when clicking AI credits option', () => {
render(<UsagePrioritySection value="apiKey" onSelect={onSelect} />)
fireEvent.click(screen.getAllByRole('button')[0]!)
fireEvent.click(getAiCreditsButton())
expect(onSelect).toHaveBeenCalledWith(PreferredProviderTypeEnum.system)
})
@ -58,7 +58,7 @@ describe('UsagePrioritySection', () => {
it('should call onSelect with custom when clicking API key option', () => {
render(<UsagePrioritySection value="credits" onSelect={onSelect} />)
fireEvent.click(screen.getAllByRole('button')[1]!)
fireEvent.click(getApiKeyButton())
expect(onSelect).toHaveBeenCalledWith(PreferredProviderTypeEnum.custom)
})

View File

@ -26,7 +26,7 @@ export default function UsagePrioritySection({ value, disabled, onSelect }: Usag
<div className="p-1">
<div className="flex items-center gap-1 rounded-lg p-1">
<div className="shrink-0 px-0.5 py-1">
<span className="i-ri-arrow-up-double-line block h-4 w-4 text-text-tertiary" />
<span aria-hidden="true" className="i-ri-arrow-up-double-line block h-4 w-4 text-text-tertiary" />
</div>
<div className="flex min-w-0 flex-1 items-center gap-0.5 py-0.5">
<span className="truncate system-sm-medium text-text-secondary">
@ -37,22 +37,27 @@ export default function UsagePrioritySection({ value, disabled, onSelect }: Usag
</Infotip>
</div>
<div className="flex shrink-0 items-center gap-1">
{options.map(option => (
<button
key={option.key}
type="button"
className={cn(
'shrink-0 rounded-md px-2 py-1 text-center whitespace-nowrap transition-colors focus-visible:ring-2 focus-visible:ring-components-button-primary-border focus-visible:outline-hidden disabled:opacity-50',
selectedKey === option.key
? 'border-[1.5px] border-components-option-card-option-selected-border bg-components-panel-bg system-xs-medium text-text-primary shadow-xs'
: 'border border-components-option-card-option-border bg-components-option-card-option-bg system-xs-regular text-text-secondary hover:bg-components-option-card-option-bg-hover',
)}
disabled={disabled}
onClick={() => onSelect(option.key)}
>
{t(option.labelKey, { ns: 'common' })}
</button>
))}
{options.map((option) => {
const selected = selectedKey === option.key
return (
<button
key={option.key}
type="button"
aria-pressed={selected}
className={cn(
'shrink-0 rounded-md px-2 py-1 text-center whitespace-nowrap transition-colors focus-visible:ring-2 focus-visible:ring-components-button-primary-border focus-visible:outline-hidden disabled:opacity-50',
selected
? 'border-[1.5px] border-components-option-card-option-selected-border bg-components-panel-bg system-xs-medium text-text-primary shadow-xs'
: 'border border-components-option-card-option-border bg-components-option-card-option-bg system-xs-regular text-text-secondary hover:bg-components-option-card-option-bg-hover',
)}
disabled={disabled}
onClick={() => onSelect(option.key)}
>
{t(option.labelKey, { ns: 'common' })}
</button>
)
})}
</div>
</div>
</div>

View File

@ -1,6 +1,6 @@
import type * as React from 'react'
import type { TriggerSubscriptionBuilder } from '@/app/components/workflow/block-selector/types'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SupportedCreationMethods } from '@/app/components/plugins/types'
import { TriggerCredentialTypeEnum } from '@/app/components/workflow/block-selector/types'
@ -134,36 +134,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
}),
}))
vi.mock('@/app/components/base/modal/modal', () => ({
default: ({
children,
onClose,
onConfirm,
title,
confirmButtonText,
bottomSlot,
size,
disabled,
}: {
children: React.ReactNode
onClose: () => void
onConfirm: () => void
title: string
confirmButtonText: string
bottomSlot?: React.ReactNode
size?: string
disabled?: boolean
}) => (
<div data-testid="modal" data-size={size} data-disabled={disabled}>
<div data-testid="modal-title">{title}</div>
<div data-testid="modal-content">{children}</div>
<div data-testid="modal-bottom-slot">{bottomSlot}</div>
<button data-testid="modal-confirm" onClick={onConfirm} disabled={disabled}>{confirmButtonText}</button>
<button data-testid="modal-close" onClick={onClose}>Close</button>
</div>
),
}))
type MockFormValuesConfig = {
values: Record<string, unknown>
isCheckValidated: boolean

View File

@ -1,8 +1,15 @@
'use client'
import type { TriggerSubscriptionBuilder } from '@/app/components/workflow/block-selector/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
Dialog,
DialogCloseButton,
DialogContent,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { useTranslation } from 'react-i18next'
import { EncryptedBottom } from '@/app/components/base/encrypted-bottom'
import Modal from '@/app/components/base/modal/modal'
import { SupportedCreationMethods } from '@/app/components/plugins/types'
import {
ConfigurationStepContent,
@ -48,46 +55,93 @@ export const CommonCreateModal = ({ onClose, createType, builder }: Props) => {
const isApiKeyType = createType === SupportedCreationMethods.APIKEY
const isVerifyStep = currentStep === ApiKeyStep.Verify
const isConfigurationStep = currentStep === ApiKeyStep.Configuration
const isDisabled = isVerifyingCredentials || isBuilding
const modalSize = createType === SupportedCreationMethods.MANUAL ? 'md' : 'sm'
return (
<Modal
title={t(MODAL_TITLE_KEY_MAP[createType], { ns: 'pluginTrigger' })}
confirmButtonText={confirmButtonText}
onClose={onClose}
onCancel={onClose}
onConfirm={handleConfirm}
disabled={isVerifyingCredentials || isBuilding}
bottomSlot={isVerifyStep ? <EncryptedBottom /> : null}
size={createType === SupportedCreationMethods.MANUAL ? 'md' : 'sm'}
containerClassName="min-h-[360px]"
clickOutsideNotClose
>
{isApiKeyType && <MultiSteps currentStep={currentStep} />}
<Dialog open disablePointerDismissal>
<DialogContent
backdropProps={{ forceRender: true }}
className={cn(
'flex max-h-[80%] min-h-[360px] flex-col overflow-hidden p-0 shadow-xs',
modalSize === 'md'
? 'w-[640px] max-w-[calc(100vw-2rem)]'
: 'w-[480px] max-w-[calc(100vw-2rem)]',
)}
>
<div
className="flex min-h-0 flex-1 flex-col"
data-testid="modal"
data-size={modalSize}
data-disabled={isDisabled}
>
<div className="relative shrink-0 p-6 pr-14 pb-3">
<DialogTitle className="title-2xl-semi-bold text-text-primary" data-testid="modal-title">
{t(MODAL_TITLE_KEY_MAP[createType], { ns: 'pluginTrigger' })}
</DialogTitle>
<DialogCloseButton
className="top-5 right-5 h-8 w-8 rounded-lg [&>span]:h-5 [&>span]:w-5"
data-testid="modal-close"
onClick={onClose}
/>
</div>
{isVerifyStep && (
<VerifyStepContent
apiKeyCredentialsSchema={apiKeyCredentialsSchema}
apiKeyCredentialsFormRef={formRefs.apiKeyCredentialsFormRef}
onChange={handleApiKeyCredentialsChange}
/>
)}
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-3">
{isApiKeyType && <MultiSteps currentStep={currentStep} />}
{isConfigurationStep && (
<ConfigurationStepContent
createType={createType}
subscriptionBuilder={subscriptionBuilder}
subscriptionFormRef={formRefs.subscriptionFormRef}
autoCommonParametersSchema={autoCommonParametersSchema}
autoCommonParametersFormRef={formRefs.autoCommonParametersFormRef}
manualPropertiesSchema={manualPropertiesSchema}
manualPropertiesFormRef={formRefs.manualPropertiesFormRef}
onManualPropertiesChange={handleManualPropertiesChange}
logs={logData?.logs || []}
pluginId={detail?.plugin_id || ''}
pluginName={detail?.name || ''}
provider={detail?.provider || ''}
/>
)}
</Modal>
{isVerifyStep && (
<VerifyStepContent
apiKeyCredentialsSchema={apiKeyCredentialsSchema}
apiKeyCredentialsFormRef={formRefs.apiKeyCredentialsFormRef}
onChange={handleApiKeyCredentialsChange}
/>
)}
{isConfigurationStep && (
<ConfigurationStepContent
createType={createType}
subscriptionBuilder={subscriptionBuilder}
subscriptionFormRef={formRefs.subscriptionFormRef}
autoCommonParametersSchema={autoCommonParametersSchema}
autoCommonParametersFormRef={formRefs.autoCommonParametersFormRef}
manualPropertiesSchema={manualPropertiesSchema}
manualPropertiesFormRef={formRefs.manualPropertiesFormRef}
onManualPropertiesChange={handleManualPropertiesChange}
logs={logData?.logs || []}
pluginId={detail?.plugin_id || ''}
pluginName={detail?.name || ''}
provider={detail?.provider || ''}
/>
)}
</div>
<div className="flex shrink-0 justify-end p-6 pt-5">
<div className="flex items-center">
<Button
disabled={isDisabled}
onClick={onClose}
>
{t('operation.cancel', { ns: 'common' })}
</Button>
<Button
className="ml-2"
variant="primary"
disabled={isDisabled}
data-testid="modal-confirm"
onClick={handleConfirm}
>
{confirmButtonText}
</Button>
</div>
</div>
{isVerifyStep && (
<div className="shrink-0">
<EncryptedBottom />
</div>
)}
</div>
</DialogContent>
</Dialog>
)
}

View File

@ -14,6 +14,7 @@ import type {
OnSelectBlock,
ToolWithProvider,
} from '../types'
import { cn } from '@langgenius/dify-ui/cn'
import {
Popover,
PopoverContent,
@ -209,24 +210,27 @@ const NodeSelector: FC<NodeSelectorProps> = ({
}, [activeTab, t])
const defaultTriggerElement = (
<div
className={`
z-10 flex h-4
w-4 cursor-pointer items-center justify-center rounded-full bg-components-button-primary-bg text-text-primary-on-surface hover:bg-components-button-primary-bg-hover
${triggerClassName?.(open)}
`}
<PopoverTrigger
aria-label={t('common.addBlock', { ns: 'workflow' })}
className={cn(
'z-10 flex h-4 w-4 cursor-pointer items-center justify-center rounded-full border-0 bg-components-button-primary-bg p-0 text-text-primary-on-surface hover:bg-components-button-primary-bg-hover focus-visible:ring-1 focus-visible:ring-components-input-border-hover focus-visible:outline-hidden',
triggerClassName?.(open),
)}
style={triggerStyle}
onClick={handleTrigger}
>
<Plus02 className="h-2.5 w-2.5" />
</div>
<Plus02 aria-hidden className="h-2.5 w-2.5" />
</PopoverTrigger>
)
const triggerElement = trigger ? trigger(open) : defaultTriggerElement
const triggerElement = trigger?.(open)
const shouldRenderTriggerElementAsRoot = React.isValidElement(triggerElement)
&& (asChild || triggerElement.type === 'button')
const triggerElementProps = React.isValidElement(triggerElement)
? (triggerElement.props as {
onClick?: MouseEventHandler<HTMLElement>
})
: null
const resolvedTriggerElement = asChild && React.isValidElement(triggerElement)
const resolvedTriggerElement = shouldRenderTriggerElementAsRoot
? React.cloneElement(
triggerElement as React.ReactElement<{
onClick?: MouseEventHandler<HTMLElement>
@ -247,8 +251,7 @@ const NodeSelector: FC<NodeSelectorProps> = ({
const resolvedOffset = typeof offset === 'number' || typeof offset === 'function' ? undefined : offset
const sideOffset = typeof offset === 'number' ? offset : (resolvedOffset?.mainAxis ?? 0)
const alignOffset = typeof offset === 'number' ? 0 : (resolvedOffset?.crossAxis ?? 0)
const nativeButton = asChild
&& React.isValidElement(triggerElement)
const nativeButton = shouldRenderTriggerElementAsRoot
&& (typeof triggerElement.type !== 'string' || triggerElement.type === 'button')
return (
@ -256,7 +259,9 @@ const NodeSelector: FC<NodeSelectorProps> = ({
open={open}
onOpenChange={handleOpenChange}
>
<PopoverTrigger nativeButton={nativeButton} render={resolvedTriggerElement as React.ReactElement} />
{trigger
? <PopoverTrigger nativeButton={nativeButton} render={resolvedTriggerElement as React.ReactElement} />
: defaultTriggerElement}
<PopoverContent
placement={placement}
sideOffset={sideOffset}

View File

@ -230,6 +230,7 @@ const VarReferencePickerTrigger: FC<Props> = ({
? variablePicker
: (
<PopoverTrigger
nativeButton={false}
render={variablePicker}
onClick={handleTriggerReadonlyClick}
/>
@ -344,6 +345,7 @@ const VarReferencePickerTrigger: FC<Props> = ({
return (
<PopoverTrigger
nativeButton={false}
render={triggerContent}
onClick={handleTriggerReadonlyClick}
/>

View File

@ -28,7 +28,7 @@ const ParameterTable: FC<ParameterTableProps> = ({
}) => {
const { t } = useTranslation()
// Memoize typeOptions to prevent unnecessary re-renders that cause SimpleSelect state resets
// Memoize typeOptions to prevent unnecessary re-renders that cause Select state resets
const typeOptions = useMemo(() =>
createParameterTypeOptions(contentType), [contentType])

View File

@ -0,0 +1,57 @@
import { useSuspenseQuery } from '@tanstack/react-query'
import { fireEvent, render, screen } from '@testing-library/react'
import { setLocaleOnClient } from '@/i18n-config'
import Header from '../_header'
vi.mock('@tanstack/react-query', () => ({
useSuspenseQuery: vi.fn(),
}))
vi.mock('@/context/i18n', () => ({
useLocale: () => 'en-US',
}))
vi.mock('@/i18n-config', () => ({
setLocaleOnClient: vi.fn(),
}))
vi.mock('@/next/dynamic', () => ({
default: () => () => null,
}))
vi.mock('@/service/system-features', () => ({
systemFeaturesQueryOptions: () => ({}),
}))
vi.mock('../_locale-menu', () => ({
default: ({ onChange }: { onChange?: (value: string) => void }) => (
<button type="button" onClick={() => onChange?.('ja-JP')}>
Switch Language
</button>
),
}))
const mockUseSuspenseQuery = vi.mocked(useSuspenseQuery)
const mockSetLocaleOnClient = vi.mocked(setLocaleOnClient)
describe('Signin Header', () => {
beforeEach(() => {
vi.clearAllMocks()
mockUseSuspenseQuery.mockReturnValue({
data: {
branding: {
enabled: false,
login_page_logo: '',
},
},
} as ReturnType<typeof useSuspenseQuery>)
})
it('should switch locale without forcing a full page reload', () => {
render(<Header />)
fireEvent.click(screen.getByRole('button', { name: 'Switch Language' }))
expect(mockSetLocaleOnClient).toHaveBeenCalledWith('ja-JP', false)
})
})

View File

@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import LocaleSelect from '../locale'
import LocaleMenu from '../_locale-menu'
const localeItems = [
{ value: 'en-US', name: 'English (US)' },
@ -8,16 +8,15 @@ const localeItems = [
{ value: 'ja-JP', name: '日本語' },
]
describe('LocaleSelect', () => {
describe('LocaleMenu', () => {
beforeEach(() => {
vi.clearAllMocks()
})
// Rendering behavior for selected value and fallback state.
describe('Rendering', () => {
it('should render selected locale name when value matches an item', () => {
render(
<LocaleSelect
<LocaleMenu
items={localeItems}
value="en-US"
onChange={vi.fn()}
@ -29,7 +28,7 @@ describe('LocaleSelect', () => {
it('should render trigger without selected label when value is not found', () => {
render(
<LocaleSelect
<LocaleMenu
items={localeItems}
value="missing"
onChange={vi.fn()}
@ -42,14 +41,13 @@ describe('LocaleSelect', () => {
})
})
// Menu interactions and callback behavior.
describe('User Interactions', () => {
it('should call onChange with selected locale value when clicking an option', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<LocaleSelect
<LocaleMenu
items={localeItems}
value="en-US"
onChange={onChange}
@ -57,7 +55,7 @@ describe('LocaleSelect', () => {
)
await user.click(screen.getByRole('button', { name: /english \(us\)/i }))
await user.click(screen.getByRole('menuitem', { name: '日本語' }))
await user.click(screen.getByRole('menuitemradio', { name: '日本語' }))
expect(onChange).toHaveBeenCalledWith('ja-JP')
})
@ -66,7 +64,7 @@ describe('LocaleSelect', () => {
const user = userEvent.setup()
render(
<LocaleSelect
<LocaleMenu
items={localeItems}
value="en-US"
onChange={vi.fn()}
@ -75,33 +73,34 @@ describe('LocaleSelect', () => {
await user.click(screen.getByRole('button', { name: /english \(us\)/i }))
expect(screen.getByRole('menuitem', { name: 'English (US)' })).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: '简体中文' })).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: '日本語' })).toBeInTheDocument()
expect(screen.getByRole('menuitemradio', { name: 'English (US)' })).toBeInTheDocument()
expect(screen.getByRole('menuitemradio', { name: '简体中文' })).toBeInTheDocument()
expect(screen.getByRole('menuitemradio', { name: '日本語' })).toBeInTheDocument()
})
})
// Edge behavior for missing callback and empty data.
describe('Edge Cases', () => {
it('should not throw when onChange is undefined and option is selected', async () => {
const user = userEvent.setup()
render(
<LocaleSelect
<LocaleMenu
items={localeItems}
value="en-US"
/>,
)
await user.click(screen.getByRole('button', { name: /english \(us\)/i }))
await user.click(screen.getByRole('menuitem', { name: '简体中文' }))
await user.click(screen.getByRole('menuitemradio', { name: '简体中文' }))
expect(screen.queryByRole('menuitemradio', { name: '简体中文' })).not.toBeInTheDocument()
})
it('should render no options when items are empty', async () => {
const user = userEvent.setup()
render(
<LocaleSelect
<LocaleMenu
items={[]}
value="en-US"
onChange={vi.fn()}
@ -109,7 +108,8 @@ describe('LocaleSelect', () => {
)
await user.click(screen.getByRole('button'))
expect(screen.queryAllByRole('menuitem')).toHaveLength(0)
expect(screen.queryAllByRole('menuitemradio')).toHaveLength(0)
})
})
})

View File

@ -1,13 +1,12 @@
'use client'
import type { Locale } from '@/i18n-config'
import { useSuspenseQuery } from '@tanstack/react-query'
import Divider from '@/app/components/base/divider'
import LocaleSigninSelect from '@/app/components/base/select/locale-signin'
import { useLocale } from '@/context/i18n'
import { setLocaleOnClient } from '@/i18n-config'
import { languages } from '@/i18n-config/language'
import dynamic from '@/next/dynamic'
import { systemFeaturesQueryOptions } from '@/service/system-features'
import LocaleMenu from './_locale-menu'
// Avoid rendering the logo and theme selector on the server
const DifyLogo = dynamic(() => import('@/app/components/base/logo/dify-logo'), {
@ -35,11 +34,11 @@ const Header = () => {
)
: <DifyLogo size="large" />}
<div className="flex items-center gap-1">
<LocaleSigninSelect
<LocaleMenu
value={locale}
items={languages.filter(item => item.supported)}
onChange={(value) => {
setLocaleOnClient(value as Locale)
setLocaleOnClient(value, false)
}}
/>
<Divider type="vertical" className="mx-0 ml-2 h-4" />

View File

@ -0,0 +1,73 @@
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuRadioItemIndicator,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
type LocaleMenuItem<T extends string> = {
value: T
name: string
}
type LocaleMenuProps<T extends string> = {
items: Array<LocaleMenuItem<T>>
value?: T
onChange?: (value: T) => void
}
export default function LocaleMenu<T extends string>({
items,
value,
onChange,
}: LocaleMenuProps<T>) {
const selectedItem = items.find(item => item.value === value)
const handleValueChange = (nextValue: string) => {
const nextItem = items.find(item => item.value === nextValue)
if (nextItem)
onChange?.(nextItem.value)
}
return (
<div className="w-56 text-right">
<DropdownMenu>
<div className="relative inline-block text-left">
<div>
<DropdownMenuTrigger
render={(
<button
type="button"
className="inline-flex w-full items-center rounded-lg border border-components-button-secondary-border px-[10px] py-[6px] text-[13px] font-medium text-text-primary hover:bg-state-base-hover"
/>
)}
>
<span className="mr-1 i-heroicons-globe-alt h-5 w-5" aria-hidden="true" />
{selectedItem?.name}
</DropdownMenuTrigger>
</div>
</div>
<DropdownMenuContent
placement="bottom-end"
sideOffset={8}
popupClassName="w-[200px]"
>
<DropdownMenuRadioGroup value={value} onValueChange={handleValueChange}>
{items.map(item => (
<DropdownMenuRadioItem
key={item.value}
value={item.value}
closeOnClick
className="px-3 py-2 text-sm text-text-secondary"
>
<span className="grow truncate">{item.name}</span>
<DropdownMenuRadioItemIndicator />
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
)
}

View File

@ -10,7 +10,6 @@ This document tracks the Dify-web migration away from legacy overlay APIs.
- `@/app/components/base/portal-to-follow-elem`
- `@/app/components/base/tooltip`
- `@/app/components/base/modal`
- `@/app/components/base/select` (including `custom` / `pure`)
- `@/app/components/base/dialog`
- Replacement primitives:
- `@langgenius/dify-ui/tooltip`

View File

@ -58,15 +58,6 @@ export const OVERLAY_RESTRICTED_IMPORT_PATTERNS = [
],
message: 'Deprecated: use @langgenius/dify-ui/dialog instead. See issue #32767.',
},
{
group: [
'**/base/select',
'**/base/select/index',
'**/base/select/custom',
'**/base/select/pure',
],
message: 'Deprecated: use @langgenius/dify-ui/select instead. See issue #32767.',
},
{
group: [
'**/base/dialog',
@ -89,9 +80,6 @@ export const OVERLAY_MIGRATION_LEGACY_BASE_FILES = [
'app/components/base/modal/modal.tsx',
'app/components/base/prompt-editor/plugins/context-block/component.tsx',
'app/components/base/prompt-editor/plugins/history-block/component.tsx',
'app/components/base/select/custom.tsx',
'app/components/base/select/index.tsx',
'app/components/base/select/pure.tsx',
'app/components/base/sort/index.tsx',
'app/components/base/theme-selector.tsx',
'app/components/base/tooltip/index.tsx',