Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(web): correct form labels, validation feedback, and keyboard navigation (#42096)

Joel1a415d1e02fc
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index b1f16f0907f..4b8ee80ff96 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -318,14 +318,6 @@
"count": 4
}
},
- "web/app/components/app/configuration/config-var/config-select/index.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/app/components/app/configuration/config-var/config-string/index.tsx": {
"no-restricted-imports": {
"count": 1
diff --git a/packages/dify-ui/src/textarea/__tests__/index.spec.tsx b/packages/dify-ui/src/textarea/__tests__/index.spec.tsx
index 9473671aa32..6827cbcba6b 100644
--- a/packages/dify-ui/src/textarea/__tests__/index.spec.tsx
+++ b/packages/dify-ui/src/textarea/__tests__/index.spec.tsx
@@ -1,4 +1,5 @@
import * as React from 'react'
+import { userEvent } from 'vite-plus/test/browser'
import { render } from 'vitest-browser-react'
import { Field, FieldDescription, FieldError, FieldLabel } from '../../field'
import { Form } from '../../form'
@@ -7,6 +8,19 @@ import { Textarea } from '../index'
const asHTMLElement = (element: HTMLElement | SVGElement) => element as HTMLElement
describe('Textarea', () => {
+ it('should show keyboard focus when read-only', async () => {
+ const screen = await render(<Textarea aria-label="Notes" defaultValue="Saved notes" readOnly />)
+ const textarea = screen.getByRole('textbox', { name: 'Notes' })
+ const restingBoxShadow = getComputedStyle(textarea.element()).boxShadow
+
+ await userEvent.keyboard('{Tab}')
+
+ await expect.element(textarea).toHaveFocus()
+ await expect
+ .poll(() => getComputedStyle(textarea.element()).boxShadow)
+ .not.toBe(restingBoxShadow)
+ })
+
it('should render a labelled textarea through Base UI Field.Control', async () => {
const screen = await render(
<Field name="description">
diff --git a/packages/dify-ui/src/textarea/index.tsx b/packages/dify-ui/src/textarea/index.tsx
index 2ec656416db..cbbad7cc52f 100644
--- a/packages/dify-ui/src/textarea/index.tsx
+++ b/packages/dify-ui/src/textarea/index.tsx
@@ -15,7 +15,7 @@ const textareaVariants = cva(
'hover:border-components-input-border-hover hover:bg-components-input-bg-hover',
textControlFocusClassName,
'data-invalid:border-components-input-border-destructive data-invalid:bg-components-input-bg-destructive',
- 'read-only:cursor-default read-only:shadow-none read-only:hover:border-transparent read-only:hover:bg-components-input-bg-normal read-only:focus:border-transparent read-only:focus:bg-components-input-bg-normal read-only:focus:shadow-none',
+ 'read-only:cursor-default read-only:shadow-none read-only:hover:border-transparent read-only:hover:bg-components-input-bg-normal read-only:focus:border-transparent read-only:focus:bg-components-input-bg-normal read-only:focus:shadow-none read-only:focus-visible:ring-2 read-only:focus-visible:ring-state-accent-solid',
'disabled:cursor-not-allowed disabled:border-transparent disabled:bg-components-input-bg-disabled disabled:text-components-input-text-filled-disabled',
'disabled:hover:border-transparent disabled:hover:bg-components-input-bg-disabled',
'motion-reduce:transition-none',
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
index 759d172a071..2ef09f39557 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
@@ -84,23 +84,6 @@ vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', (
),
}))
-vi.mock('../field', () => ({
- default: ({ children, title }: { children: ReactNode; title: string }) => (
- <div>
- <span>{title}</span>
- {children}
- </div>
- ),
-}))
-
-vi.mock('../type-select', () => ({
- default: ({ onSelect }: { onSelect: (item: { value: InputVarType }) => void }) => (
- <button type="button" onClick={() => onSelect({ value: InputVarType.select })}>
- type-selector
- </button>
- ),
-}))
-
vi.mock('../../config-select', () => ({
default: ({ onChange }: { onChange: (value: string[]) => void }) => (
<button type="button" onClick={() => onChange(['alpha', 'beta'])}>
@@ -147,7 +130,11 @@ const createBaseProps = () => {
onVarKeyBlur: vi.fn(),
onVarNameChange: vi.fn(),
options: undefined as string[] | undefined,
- selectOptions: [],
+ selectOptions: [
+ { value: InputVarType.textInput, name: 'Text' },
+ { value: InputVarType.select, name: 'Select' },
+ { value: InputVarType.checkbox, name: 'Checkbox' },
+ ],
tempPayload: {
type: InputVarType.textInput,
label: 'Question',
@@ -161,6 +148,46 @@ const createBaseProps = () => {
}
describe('ConfigModalFormFields', () => {
+ it.each([
+ {
+ type: InputVarType.textInput,
+ label: 'variableConfig.fieldType',
+ option: 'Select',
+ value: InputVarType.select,
+ },
+ {
+ type: InputVarType.checkbox,
+ label: 'variableConfig.defaultValue',
+ option: 'variableConfig.startChecked',
+ value: true,
+ },
+ {
+ type: InputVarType.select,
+ label: 'variableConfig.defaultValue',
+ option: 'beta',
+ value: 'beta',
+ },
+ ])(
+ 'should focus the $type selector from its label and select an option',
+ async ({ type, label, option, value }) => {
+ const user = userEvent.setup()
+ const props = createBaseProps()
+ props.tempPayload.type = type
+ props.options = ['alpha', 'beta']
+ render(<ConfigModalFormFields {...props} />)
+
+ await user.click(screen.getByText(label))
+ const trigger = screen.getByRole('combobox', { name: label })
+ expect(trigger).toHaveFocus()
+ await user.keyboard('{ArrowDown}')
+ await user.click(await screen.findByRole('option', { name: new RegExp(`^${option}`) }))
+
+ if (type === InputVarType.textInput)
+ expect(props.onTypeChange).toHaveBeenCalledWith({ value, name: option })
+ else expect(props.payloadChangeHandlers.default).toHaveBeenCalledWith(value)
+ },
+ )
+
it('should update paragraph, number, checkbox, and select defaults', async () => {
const user = userEvent.setup()
const paragraphProps = createBaseProps()
@@ -191,7 +218,7 @@ describe('ConfigModalFormFields', () => {
}
checkboxProps.checkboxDefaultSelectValue = 'true'
const checkboxView = render(<ConfigModalFormFields {...checkboxProps} />)
- await user.click(screen.getByRole('combobox'))
+ await user.click(screen.getByRole('combobox', { name: 'variableConfig.defaultValue' }))
const checkboxOptions = await screen.findAllByRole('option')
await user.click(checkboxOptions[1]!)
expect(checkboxProps.payloadChangeHandlers.default).toHaveBeenCalledWith(false)
@@ -206,7 +233,7 @@ describe('ConfigModalFormFields', () => {
selectProps.options = ['alpha', 'beta']
render(<ConfigModalFormFields {...selectProps} />)
fireEvent.click(screen.getByText('config-select'))
- await user.click(screen.getByRole('combobox'))
+ await user.click(screen.getByRole('combobox', { name: 'variableConfig.defaultValue' }))
const selectOptions = await screen.findAllByRole('option')
await user.click(selectOptions[2]!)
expect(selectProps.payloadChangeHandlers.options).toHaveBeenCalledWith(['alpha', 'beta'])
@@ -299,14 +326,12 @@ describe('ConfigModalFormFields', () => {
const variableInput = screen.getByDisplayValue('question')
- fireEvent.click(screen.getByText('type-selector'))
fireEvent.change(variableInput, { target: { value: 'prompt' } })
fireEvent.blur(variableInput)
fireEvent.change(screen.getByDisplayValue('Question'), { target: { value: 'Prompt Label' } })
fireEvent.click(screen.getByText('config-string'))
fireEvent.change(screen.getByDisplayValue('hello'), { target: { value: '' } })
- expect(textProps.onTypeChange).toHaveBeenCalledWith({ value: InputVarType.select })
expect(textProps.onVarNameChange).toHaveBeenCalled()
expect(textProps.onVarKeyBlur).toHaveBeenCalled()
expect(textProps.payloadChangeHandlers.label).toHaveBeenCalledWith('Prompt Label')
@@ -325,7 +350,7 @@ describe('ConfigModalFormFields', () => {
selectProps.options = ['alpha', ' ', 'beta']
const selectView = render(<ConfigModalFormFields {...selectProps} />)
- await user.click(screen.getByRole('combobox'))
+ await user.click(screen.getByRole('combobox', { name: 'variableConfig.defaultValue' }))
const selectOptions = await screen.findAllByRole('option')
await user.click(selectOptions[0]!)
expect(selectProps.payloadChangeHandlers.default).toHaveBeenCalledWith(undefined)
@@ -386,7 +411,9 @@ describe('ConfigModalFormFields', () => {
render(<ConfigModalFormFields {...selectWithoutOptionsProps} />)
expect(screen.getAllByText('config-select')).toHaveLength(1)
- expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('combobox', { name: 'variableConfig.defaultValue' }),
+ ).not.toBeInTheDocument()
})
it('should preserve existing file defaults when present', () => {
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx
index 6207d846a05..f2c3b81278f 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx
@@ -1,11 +1,12 @@
import type { InputVar } from '@/app/components/workflow/types'
import type { App, AppSSO } from '@/types/app'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
import { toast } from '@/app/components/app/configuration/toast'
import { useStore } from '@/app/components/app/store'
import { InputVarType } from '@/app/components/workflow/types'
import DebugConfigurationContext from '@/context/debug-configuration'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { AppModeEnum } from '@/types/app'
import ConfigModal from '../index'
@@ -22,18 +23,21 @@ vi.mock('../form-fields', () => ({
<div data-testid="payload-schema">{String(props.tempPayload.json_schema ?? '')}</div>
<div data-testid="payload-default">{String(props.tempPayload.default ?? '')}</div>
<button
+ type="button"
data-testid="invalid-key-blur"
onClick={() => props.onVarKeyBlur({ target: { value: 'invalid key' } })}
>
invalid-key-blur
</button>
<button
+ type="button"
data-testid="valid-key-blur"
onClick={() => props.onVarKeyBlur({ target: { value: 'auto_label' } })}
>
valid-key-blur
</button>
<button
+ type="button"
data-testid="invalid-name-change"
onClick={() =>
props.onVarNameChange({
@@ -49,27 +53,35 @@ vi.mock('../form-fields', () => ({
invalid-name-change
</button>
<button
+ type="button"
data-testid="valid-json-change"
onClick={() => props.onJSONSchemaChange('{\n "foo": "bar"\n}')}
>
valid-json-change
</button>
- <button data-testid="empty-json-change" onClick={() => props.onJSONSchemaChange(' ')}>
+ <button
+ type="button"
+ data-testid="empty-json-change"
+ onClick={() => props.onJSONSchemaChange(' ')}
+ >
empty-json-change
</button>
<button
+ type="button"
data-testid="invalid-json-change"
onClick={() => props.onJSONSchemaChange('{invalid-json}')}
>
invalid-json-change
</button>
<button
+ type="button"
data-testid="type-change"
onClick={() => props.onTypeChange({ value: InputVarType.singleFile })}
>
type-change
</button>
<button
+ type="button"
data-testid="file-payload-change"
onClick={() =>
props.onFilePayloadChange({ ...props.tempPayload, default: 'file-default' })
@@ -155,7 +167,7 @@ describe('ConfigModal logic', () => {
})
fireEvent.click(screen.getByTestId('invalid-json-change'))
- expect(screen.getByTestId('payload-schema')).toHaveTextContent(/"foo": "bar"/)
+ expect(screen.getByTestId('payload-schema')).toHaveTextContent('{invalid-json}')
fireEvent.click(screen.getByTestId('empty-json-change'))
await waitFor(() => {
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx
index 4bca4e5db92..27a070c2839 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx
@@ -1,14 +1,37 @@
import type { InputVar } from '@/app/components/workflow/types'
import type { App, AppSSO } from '@/types/app'
import { fireEvent, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { toast } from '@/app/components/app/configuration/toast'
import { useStore } from '@/app/components/app/store'
-import { InputVarType } from '@/app/components/workflow/types'
+import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { commonQueryKeys } from '@/service/use-common'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
-import { AppModeEnum } from '@/types/app'
+import { AppModeEnum, TransferMethod } from '@/types/app'
import ConfigModal from '../index'
+vi.mock('next/navigation', async () => ({
+ ...(await vi.importActual<typeof import('next/navigation')>('next/navigation')),
+ useParams: () => ({}),
+}))
+
+vi.mock('@/service/use-common', async () => ({
+ ...(await vi.importActual<typeof import('@/service/use-common')>('@/service/use-common')),
+ useFileUploadConfig: () => ({ data: undefined }),
+}))
+
+vi.mock('@monaco-editor/react', async () => ({
+ ...(await vi.importActual<typeof import('@monaco-editor/react')>('@monaco-editor/react')),
+ default: ({ value, onChange }: { value: string; onChange: (value: string) => void }) => (
+ <textarea
+ aria-label="JSON schema editor"
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ />
+ ),
+}))
+
const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')
const createPayload = (overrides: Partial<InputVar> = {}): InputVar => ({
@@ -75,6 +98,354 @@ describe('ConfigModal', () => {
)
})
+ it('should label editable fields and submit once when Enter is pressed', async () => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+ render(
+ <ConfigModal
+ isCreate
+ isShow
+ payload={createPayload({ label: 'Question' })}
+ onClose={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+
+ expect(screen.getByRole('textbox', { name: 'appDebug.variableConfig.varName' })).toHaveValue(
+ 'question',
+ )
+ expect(screen.getByRole('textbox', { name: 'appDebug.variableConfig.labelName' })).toHaveValue(
+ 'Question',
+ )
+ expect(
+ screen.getByRole('spinbutton', { name: 'appDebug.variableConfig.maxLength' }),
+ ).toHaveValue(32)
+ const defaultInput = screen.getByRole('textbox', {
+ name: 'appDebug.variableConfig.defaultValue',
+ })
+ await user.click(defaultInput)
+ await user.keyboard('{Enter}')
+
+ expect(onConfirm).toHaveBeenCalledTimes(1)
+ expect(onConfirm).toHaveBeenCalledWith(expect.objectContaining({ default: 'hello' }), undefined)
+ })
+
+ it.each([InputVarType.singleFile, InputVarType.multiFiles])(
+ 'should keep the %s configuration open when Enter adds custom extensions',
+ async (type) => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+ const onClose = vi.fn()
+ render(
+ <ConfigModal
+ isShow
+ supportFile
+ payload={createPayload({
+ type,
+ label: 'Attachment',
+ default: undefined,
+ max_length: 2,
+ allowed_file_types: [SupportUploadFileTypes.custom],
+ allowed_file_extensions: ['.txt'],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ })}
+ onClose={onClose}
+ onConfirm={onConfirm}
+ />,
+ )
+
+ const extensionInput = screen.getByPlaceholderText(
+ 'appDebug.variableConfig.file.custom.createPlaceholder',
+ )
+ await user.type(extensionInput, '.csv{Enter}')
+
+ expect(screen.getByRole('button', { name: 'common.operation.remove .csv' })).toBeVisible()
+ expect(extensionInput).toHaveFocus()
+ expect(onConfirm).not.toHaveBeenCalled()
+ expect(onClose).not.toHaveBeenCalled()
+ expect(screen.getByRole('dialog')).toBeVisible()
+
+ await user.type(extensionInput, '.json{Enter}')
+ expect(screen.getByRole('button', { name: 'common.operation.remove .json' })).toBeVisible()
+ expect(onConfirm).not.toHaveBeenCalled()
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ allowed_file_extensions: ['.txt', '.csv', '.json'] }),
+ undefined,
+ )
+ },
+ )
+
+ it.each(['Enter', 'Save'])(
+ 'should fill an empty upload count on %s submission',
+ async (method) => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+ render(
+ <ConfigModal
+ isShow
+ supportFile
+ payload={createPayload({
+ type: InputVarType.multiFiles,
+ label: 'Attachment',
+ default: undefined,
+ max_length: 2,
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ })}
+ onClose={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+
+ const count = screen.getByRole('spinbutton', {
+ name: 'appDebug.variableConfig.maxNumberOfUploads',
+ })
+ await user.click(count)
+ await user.clear(count)
+ expect(count).toHaveFocus()
+ if (method === 'Enter') await user.keyboard('{Enter}')
+ else await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ max_length: 1 }),
+ undefined,
+ )
+ },
+ )
+
+ it('should clamp the upload count to the current cached server limit on submission', async () => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+ const { queryClient } = render(
+ <ConfigModal
+ isShow
+ supportFile
+ payload={createPayload({
+ type: InputVarType.multiFiles,
+ label: 'Attachment',
+ default: undefined,
+ max_length: 5,
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ })}
+ onClose={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+ queryClient.setQueryData(commonQueryKeys.fileUploadConfig, {
+ batch_count_limit: 5,
+ image_file_batch_limit: 10,
+ single_chunk_attachment_limit: 10,
+ attachment_image_file_size_limit: 2,
+ file_size_limit: 15,
+ file_upload_limit: 5,
+ workflow_file_upload_limit: 3,
+ })
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ max_length: 3 }),
+ undefined,
+ )
+ })
+
+ it.each([
+ { field: 'variable', name: 'appDebug.variableConfig.varName' },
+ { field: 'label', name: 'appDebug.variableConfig.labelName' },
+ ] as const)(
+ 'should focus and describe the invalid $field and clear its error after editing',
+ async ({ field, name }) => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+ render(
+ <ConfigModal
+ isShow
+ payload={createPayload({ label: field === 'variable' ? '' : 'Question', [field]: '' })}
+ onClose={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+
+ const input = screen.getByRole('textbox', { name })
+ const save = screen.getByRole('button', { name: 'common.operation.save' })
+ await user.click(save)
+ expect(input).toHaveFocus()
+ expect(input).toBeInvalid()
+ expect(input).toHaveAccessibleDescription(toastErrorSpy.mock.lastCall![0])
+ expect(onConfirm).not.toHaveBeenCalled()
+
+ // Repeated invalid submissions must restore focus as well.
+ await user.click(save)
+ expect(input).toHaveFocus()
+ await user.type(input, 'question')
+ expect(input).not.toBeInvalid()
+ expect(input).not.toHaveAttribute('aria-describedby')
+ await user.click(save)
+ expect(onConfirm).toHaveBeenCalledOnce()
+ },
+ )
+
+ it.each([{ options: [] }, { options: ['alpha', 'alpha'] }])(
+ 'should associate option errors and focus an action or input',
+ async ({ options }) => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+ render(
+ <ConfigModal
+ isShow
+ payload={createPayload({
+ type: InputVarType.select,
+ label: 'Question',
+ options,
+ default: undefined,
+ })}
+ onClose={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ const control = options.length
+ ? screen.getByRole('textbox', { name: 'appDebug.variableConfig.options 1' })
+ : screen.getByRole('button', { name: 'appDebug.variableConfig.addOption' })
+ expect(control).toHaveFocus()
+ expect(control).toHaveAttribute('aria-invalid', 'true')
+ expect(control).toHaveAccessibleDescription(toastErrorSpy.mock.lastCall![0])
+ expect(onConfirm).not.toHaveBeenCalled()
+ },
+ )
+
+ it.each([
+ { types: [], role: 'checkbox', name: 'appDebug.variableConfig.file.document.name' },
+ {
+ types: [SupportUploadFileTypes.custom],
+ role: 'textbox',
+ name: 'appDebug.variableConfig.file.custom.name',
+ },
+ ])(
+ 'should focus and describe file configuration errors for $name',
+ async ({ types, role, name }) => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+ render(
+ <ConfigModal
+ isShow
+ supportFile
+ payload={createPayload({
+ type: InputVarType.singleFile,
+ label: 'Attachment',
+ default: undefined,
+ allowed_file_types: types,
+ allowed_file_extensions: [],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ })}
+ onClose={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ const control = screen.getByRole(role, { name })
+ expect(control).toHaveFocus()
+ expect(control).toHaveAttribute('aria-invalid', 'true')
+ expect(control).toHaveAccessibleDescription(toastErrorSpy.mock.lastCall![0])
+ expect(onConfirm).not.toHaveBeenCalled()
+
+ if (role === 'textbox') await user.type(control, '.csv{Enter}')
+ else await user.click(control)
+ expect(control).not.toHaveAttribute('aria-invalid')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ expect(onConfirm).toHaveBeenCalledOnce()
+ },
+ )
+
+ it('should validate the current JSON draft and associate the error with the editor group', async () => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+ render(
+ <ConfigModal
+ isShow
+ payload={createPayload({
+ type: InputVarType.jsonObject,
+ label: 'Question',
+ json_schema: '{"type":"object"}',
+ })}
+ onClose={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+
+ const editor = screen.getByRole('textbox', { name: 'JSON schema editor' })
+ await user.click(editor)
+ await user.clear(editor)
+ await user.paste('{invalid}')
+ expect(editor).toHaveValue('{invalid}')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ const group = screen.getByRole('group', { name: /appDebug.variableConfig.jsonSchema/ })
+ expect(group).toHaveFocus()
+ expect(group).toHaveAttribute('aria-invalid', 'true')
+ expect(group).toHaveAccessibleDescription('appDebug.variableConfig.errorMsg.jsonSchemaInvalid')
+ expect(onConfirm).not.toHaveBeenCalled()
+
+ await user.click(editor)
+ await user.clear(editor)
+ await user.paste('{"type":"object"}')
+ expect(group).not.toHaveAttribute('aria-invalid')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ json_schema: JSON.stringify({ type: 'object' }, null, 2) }),
+ undefined,
+ )
+ })
+
+ it.each([InputVarType.checkbox, InputVarType.select])(
+ 'should associate the default selector label for %s',
+ (type) => {
+ render(
+ <ConfigModal
+ isShow
+ payload={createPayload({
+ type,
+ label: 'Question',
+ options: ['alpha'],
+ default: undefined,
+ })}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ />,
+ )
+
+ expect(
+ screen.getByRole('combobox', { name: 'appDebug.variableConfig.fieldType' }),
+ ).toBeInTheDocument()
+ expect(
+ screen.getByRole('combobox', { name: 'appDebug.variableConfig.defaultValue' }),
+ ).toBeInTheDocument()
+ },
+ )
+
+ it('should cancel without submitting the form', async () => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+ const onClose = vi.fn()
+ render(
+ <ConfigModal
+ isShow
+ payload={createPayload({ label: 'Question' })}
+ onClose={onClose}
+ onConfirm={onConfirm}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+
+ expect(onClose).toHaveBeenCalledOnce()
+ expect(onConfirm).not.toHaveBeenCalled()
+ })
+
it('should keep scrolling inside the form body so scrollbars do not cover dialog corners', () => {
render(
<ConfigModal
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
index 763630232a1..a2d54462dcf 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
@@ -13,6 +13,7 @@ describe('TypeSelector', () => {
render(
<TypeSelector
+ label="Field type"
value="text-input"
onSelect={onSelect}
items={[
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts b/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts
index 4a2a779b3c1..ab6ce9a5ab2 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts
@@ -146,14 +146,11 @@ describe('config-modal utils', () => {
})
it('should reject duplicate select options', () => {
- const checkVariableName = vi.fn(() => true)
-
const result = validateConfigModalPayload({
tempPayload: createInputVar({
type: InputVarType.select,
options: ['alpha', 'alpha'],
}),
- checkVariableName,
payload: createInputVar({
variable: 'question',
}),
@@ -161,7 +158,6 @@ describe('config-modal utils', () => {
})
expect(result.errorMessage).toBe('variableConfig.errorMsg.optionRepeat')
- expect(checkVariableName).toHaveBeenCalledWith('question')
})
it('should require custom extensions when custom file types are enabled', () => {
@@ -171,7 +167,6 @@ describe('config-modal utils', () => {
allowed_file_types: [SupportUploadFileTypes.custom],
allowed_file_extensions: [],
}),
- checkVariableName: () => true,
payload: createInputVar(),
t,
})
@@ -185,7 +180,6 @@ describe('config-modal utils', () => {
type: InputVarType.select,
options: [],
}),
- checkVariableName: () => true,
payload: createInputVar(),
t,
})
@@ -195,7 +189,6 @@ describe('config-modal utils', () => {
type: InputVarType.singleFile,
allowed_file_types: [],
}),
- checkVariableName: () => true,
payload: createInputVar(),
t,
})
@@ -211,7 +204,6 @@ describe('config-modal utils', () => {
json_schema: '{',
}),
payload: createInputVar(),
- checkVariableName: () => true,
t,
})
@@ -221,7 +213,6 @@ describe('config-modal utils', () => {
json_schema: JSON.stringify({ type: 'string' }),
}),
payload: createInputVar(),
- checkVariableName: () => true,
t,
})
@@ -239,7 +230,6 @@ describe('config-modal utils', () => {
payload: createInputVar({
variable: 'question_old',
}),
- checkVariableName: () => true,
t,
})
@@ -259,6 +249,39 @@ describe('config-modal utils', () => {
})
})
+ it.each([
+ [Number.NaN, 1],
+ [undefined, 1],
+ [0, 1],
+ [5, 3],
+ [2, 2],
+ ])('should normalize multi-file count %s to %s at submission', (count, expected) => {
+ const result = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ type: InputVarType.multiFiles,
+ max_length: count,
+ allowed_file_types: [SupportUploadFileTypes.document],
+ }),
+ maxFileUploadLimit: 3,
+ t,
+ })
+
+ expect(result.payloadToSave?.max_length).toBe(expected)
+ })
+
+ it('should preserve an existing upload count while the server limit is unavailable', () => {
+ const result = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ type: InputVarType.multiFiles,
+ max_length: 20,
+ allowed_file_types: [SupportUploadFileTypes.document],
+ }),
+ t,
+ })
+
+ expect(result.payloadToSave?.max_length).toBe(20)
+ })
+
it('should force file inputs to stay visible when saving', () => {
const result = validateConfigModalPayload({
tempPayload: createInputVar({
@@ -268,7 +291,6 @@ describe('config-modal utils', () => {
allowed_file_extensions: [],
}),
payload: createInputVar(),
- checkVariableName: () => true,
t,
})
@@ -279,19 +301,20 @@ describe('config-modal utils', () => {
)
})
- it('should stop validation when the variable name checker rejects the payload', () => {
+ it('should associate invalid variable names with the variable field', () => {
const result = validateConfigModalPayload({
tempPayload: createInputVar({
- variable: 'invalid_name',
+ variable: 'invalid-name!',
}),
payload: createInputVar({
variable: 'question',
}),
- checkVariableName: () => false,
t,
})
- expect(result).toEqual({})
+ expect(result.errorField).toBe('variable')
+ expect(result.errorMessage).toBeTruthy()
+ expect(result.payloadToSave).toBeUndefined()
})
})
})
diff --git a/web/app/components/app/configuration/config-var/config-modal/field.tsx b/web/app/components/app/configuration/config-var/config-modal/field.tsx
index b259bed3f38..d0b072a5fa3 100644
--- a/web/app/components/app/configuration/config-var/config-modal/field.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/field.tsx
@@ -7,23 +7,46 @@ import { useTranslation } from 'react-i18next'
type Props = Readonly<{
className?: string
title: string
+ htmlFor?: string
+ titleId?: string
isOptional?: boolean
+ errorMessage?: string
+ errorId?: string
children: React.JSX.Element
}>
-const Field: FC<Props> = ({ className, title, isOptional, children }) => {
+const Field: FC<Props> = ({
+ className,
+ title,
+ htmlFor,
+ titleId,
+ isOptional,
+ errorMessage,
+ errorId,
+ children,
+}) => {
const { t } = useTranslation()
+ const Label = htmlFor ? 'label' : 'div'
return (
<div className={cn(className)}>
- <div className="system-sm-semibold leading-8! text-text-secondary">
+ <Label
+ id={titleId}
+ htmlFor={htmlFor}
+ className="block system-sm-semibold leading-8! text-text-secondary"
+ >
{title}
{isOptional && (
<span className="ml-1 system-xs-regular text-text-tertiary">
({t(($) => $['variableConfig.optional'], { ns: 'appDebug' })})
</span>
)}
- </div>
+ </Label>
<div>{children}</div>
+ {errorMessage && (
+ <p id={errorId} className="mt-1 system-xs-regular text-text-destructive">
+ {errorMessage}
+ </p>
+ )}
</div>
)
}
diff --git a/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx b/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx
index 700cbbce9dd..84f51e9e95f 100644
--- a/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx
@@ -1,6 +1,7 @@
'use client'
import type { ChangeEvent, FC } from 'react'
import type { Item as SelectOptionItem } from './type-select'
+import type { ConfigModalValidationError } from './utils'
import type { SelectorTranslate } from '@/app/components/app/configuration/utils'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { InputVar, UploadFileSetting } from '@/app/components/workflow/types'
@@ -10,6 +11,7 @@ import {
SelectItem,
SelectItemIndicator,
SelectItemText,
+ SelectLabel,
SelectList,
SelectPopup,
SelectPortal,
@@ -55,6 +57,7 @@ type ConfigModalFormFieldsProps = {
selectOptions: SelectOptionItem[]
showHiddenField?: boolean
tempPayload: InputVar
+ validationError?: ConfigModalValidationError
t: SelectorTranslate<'appDebug'>
}
@@ -74,32 +77,60 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
selectOptions,
showHiddenField = true,
tempPayload,
+ validationError,
t: rawTranslate,
}) => {
const t = getStringSelectorTranslate(rawTranslate)
const { type, label, variable } = tempPayload
const isFileInput = [InputVarType.singleFile, InputVarType.multiFiles].includes(type)
const docLink = useDocLink()
+ const fieldId = React.useId()
+ const errorId = `${fieldId}-error`
+ const getError = (field: ConfigModalValidationError['field']) =>
+ validationError?.field === field ? validationError.message : undefined
+ const getErrorProps = (field: ConfigModalValidationError['field']) => ({
+ 'aria-invalid': !!getError(field) || undefined,
+ 'aria-describedby': getError(field) ? errorId : undefined,
+ })
const hiddenDescriptionAriaLabel = t(($) => $['variableConfig.hiddenDescription'], {
ns: 'appDebug',
}).replace(/<[^>]+>/g, '')
return (
<div className="space-y-2">
- <Field title={t(($) => $['variableConfig.fieldType'], { ns: 'appDebug' })}>
- <TypeSelector value={type} items={selectOptions} onSelect={onTypeChange} />
- </Field>
+ <div>
+ <TypeSelector
+ label={t(($) => $['variableConfig.fieldType'], { ns: 'appDebug' })}
+ value={type}
+ items={selectOptions}
+ onSelect={onTypeChange}
+ />
+ </div>
- <Field title={t(($) => $['variableConfig.varName'], { ns: 'appDebug' })}>
+ <Field
+ htmlFor={`${fieldId}-variable`}
+ title={t(($) => $['variableConfig.varName'], { ns: 'appDebug' })}
+ errorMessage={getError('variable')}
+ errorId={errorId}
+ >
<Input
+ id={`${fieldId}-variable`}
+ {...getErrorProps('variable')}
value={variable}
onChange={onVarNameChange}
onBlur={onVarKeyBlur}
placeholder={t(($) => $['variableConfig.inputPlaceholder'], { ns: 'appDebug' })}
/>
</Field>
- <Field title={t(($) => $['variableConfig.labelName'], { ns: 'appDebug' })}>
+ <Field
+ htmlFor={`${fieldId}-label`}
+ title={t(($) => $['variableConfig.labelName'], { ns: 'appDebug' })}
+ errorMessage={getError('label')}
+ errorId={errorId}
+ >
<Input
+ id={`${fieldId}-label`}
+ {...getErrorProps('label')}
value={label as string}
onChange={(e) => onPayloadChange('label')(e.target.value)}
placeholder={t(($) => $['variableConfig.inputPlaceholder'], { ns: 'appDebug' })}
@@ -107,8 +138,12 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
</Field>
{isStringInput && (
- <Field title={t(($) => $['variableConfig.maxLength'], { ns: 'appDebug' })}>
+ <Field
+ htmlFor={`${fieldId}-max-length`}
+ title={t(($) => $['variableConfig.maxLength'], { ns: 'appDebug' })}
+ >
<ConfigString
+ id={`${fieldId}-max-length`}
maxLength={type === InputVarType.textInput ? TEXT_MAX_LENGTH : Infinity}
modelId={modelId}
value={maxLength}
@@ -118,8 +153,12 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
)}
{type === InputVarType.textInput && (
- <Field title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}>
+ <Field
+ htmlFor={`${fieldId}-default`}
+ title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}
+ >
<Input
+ id={`${fieldId}-default`}
value={typeof tempPayload.default === 'string' ? tempPayload.default : ''}
onChange={(e) => onPayloadChange('default')(e.target.value || undefined)}
placeholder={t(($) => $['variableConfig.inputPlaceholder'], { ns: 'appDebug' })}
@@ -128,9 +167,12 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
)}
{type === InputVarType.paragraph && (
- <Field title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}>
+ <Field
+ htmlFor={`${fieldId}-default`}
+ title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}
+ >
<Textarea
- aria-label={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}
+ id={`${fieldId}-default`}
value={String(tempPayload.default ?? '')}
onValueChange={(value) => onPayloadChange('default')(value || undefined)}
placeholder={t(($) => $['variableConfig.inputPlaceholder'], { ns: 'appDebug' })}
@@ -139,8 +181,12 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
)}
{type === InputVarType.number && (
- <Field title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}>
+ <Field
+ htmlFor={`${fieldId}-default`}
+ title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}
+ >
<Input
+ id={`${fieldId}-default`}
type="number"
value={
typeof tempPayload.default === 'number' || typeof tempPayload.default === 'string'
@@ -154,13 +200,16 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
)}
{type === InputVarType.checkbox && (
- <Field title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}>
+ <div>
<Select
value={checkboxDefaultSelectValue}
onValueChange={(value) =>
onPayloadChange('default')(value === CHECKBOX_DEFAULT_TRUE_VALUE)
}
>
+ <SelectLabel className="block w-full py-0 system-sm-semibold leading-8! text-text-secondary">
+ {t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}
+ </SelectLabel>
<SelectTrigger size="large" className="w-full">
<SelectValue
placeholder={t(($) => $['variableConfig.selectDefaultValue'], { ns: 'appDebug' })}
@@ -187,16 +236,25 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
</SelectPositioner>
</SelectPortal>
</Select>
- </Field>
+ </div>
)}
{type === InputVarType.select && (
<>
- <Field title={t(($) => $['variableConfig.options'], { ns: 'appDebug' })}>
- <ConfigSelect options={options || []} onChange={onPayloadChange('options')} />
+ <Field
+ title={t(($) => $['variableConfig.options'], { ns: 'appDebug' })}
+ errorMessage={getError('options')}
+ errorId={errorId}
+ >
+ <ConfigSelect
+ options={options || []}
+ onChange={onPayloadChange('options')}
+ errorMessage={getError('options')}
+ errorId={errorId}
+ />
</Field>
{options && options.length > 0 && (
- <Field title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}>
+ <div>
<Select<string>
key={`default-select-${options.join('-')}`}
value={
@@ -207,6 +265,9 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
onPayloadChange('default')(value === EMPTY_SELECT_VALUE ? undefined : value)
}}
>
+ <SelectLabel className="block w-full py-0 system-sm-semibold leading-8! text-text-secondary">
+ {t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}
+ </SelectLabel>
<SelectTrigger size="large" className="w-full">
<SelectValue
placeholder={t(($) => $['variableConfig.selectDefaultValue'], {
@@ -237,7 +298,7 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
</SelectPositioner>
</SelectPortal>
</Select>
- </Field>
+ </div>
)}
</>
)}
@@ -248,6 +309,13 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
payload={tempPayload as UploadFileSetting}
onChange={onFilePayloadChange}
isMultiple={type === InputVarType.multiFiles}
+ validationError={
+ validationError &&
+ (validationError.field === 'allowed_file_types' ||
+ validationError.field === 'allowed_file_extensions')
+ ? { field: validationError.field, message: validationError.message }
+ : undefined
+ }
/>
<Field title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}>
<FileUploaderInAttachmentWrapper
@@ -279,15 +347,29 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
)}
{type === InputVarType.jsonObject && (
- <Field title={t(($) => $['variableConfig.jsonSchema'], { ns: 'appDebug' })} isOptional>
- <CodeEditor
- language={CodeLanguage.json}
- value={jsonSchemaStr}
- onChange={onJSONSchemaChange}
- noWrapper
- className="h-20 overflow-y-auto rounded-[10px] bg-components-input-bg-normal p-1"
- placeholder={<div className="whitespace-pre">{jsonConfigPlaceHolder}</div>}
- />
+ <Field
+ title={t(($) => $['variableConfig.jsonSchema'], { ns: 'appDebug' })}
+ titleId={`${fieldId}-json-schema`}
+ isOptional
+ errorMessage={getError('json_schema')}
+ errorId={errorId}
+ >
+ <div
+ role="group"
+ tabIndex={-1}
+ aria-labelledby={`${fieldId}-json-schema`}
+ {...getErrorProps('json_schema')}
+ className="rounded-[10px] focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ >
+ <CodeEditor
+ language={CodeLanguage.json}
+ value={jsonSchemaStr}
+ onChange={onJSONSchemaChange}
+ noWrapper
+ className="h-20 overflow-y-auto rounded-[10px] bg-components-input-bg-normal p-1"
+ placeholder={<div className="whitespace-pre">{jsonConfigPlaceHolder}</div>}
+ />
+ </div>
</Field>
)}
diff --git a/web/app/components/app/configuration/config-var/config-modal/index.tsx b/web/app/components/app/configuration/config-var/config-modal/index.tsx
index 5ab337c7d0a..5bd67170dca 100644
--- a/web/app/components/app/configuration/config-var/config-modal/index.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/index.tsx
@@ -1,8 +1,11 @@
'use client'
import type { ChangeEvent, FC } from 'react'
import type { Item as SelectItem } from './type-select'
+import type { ConfigModalValidationError } from './utils'
import type { InputVar, InputVarType, MoreInfo } from '@/app/components/workflow/types'
+import type { FileUploadConfigResponse } from '@/models/common'
import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { useQueryClient } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -10,6 +13,7 @@ import { useContext } from 'use-context-selector'
import { toast } from '@/app/components/app/configuration/toast'
import { useStore as useAppStore } from '@/app/components/app/store'
import ConfigContext from '@/context/debug-configuration'
+import { commonQueryKeys } from '@/service/use-common'
import { AppModeEnum } from '@/types/app'
import {
checkKeys,
@@ -54,6 +58,8 @@ const ConfigModal: FC<IConfigModalProps> = ({
const [tempPayload, setTempPayload] = useState<InputVar>(() =>
normalizeSelectDefaultValue(payload || (getNewVarInWorkflow('') as any)),
)
+ const [validationError, setValidationError] = useState<ConfigModalValidationError>()
+ const queryClient = useQueryClient()
const { type, options, max_length } = tempPayload
const modalRef = useRef<HTMLDivElement>(null)
const appDetail = useAppStore((state) => state.appDetail)
@@ -67,6 +73,10 @@ const ConfigModal: FC<IConfigModalProps> = ({
// To fix the first input element auto focus, then directly close modal will raise error
if (isShow) modalRef.current?.focus()
}, [isShow])
+ useEffect(() => {
+ if (validationError)
+ modalRef.current?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus()
+ }, [validationError])
const isStringInput = isStringInputType(type)
const checkVariableName = useCallback(
@@ -88,6 +98,7 @@ const ConfigModal: FC<IConfigModalProps> = ({
const handlePayloadChange = useCallback((key: string) => {
return (value: any) => {
setTempPayload((prev) => updatePayloadField(prev, key, value))
+ setValidationError((prev) => (prev?.field === key ? undefined : prev))
}
}, [])
@@ -102,7 +113,7 @@ const ConfigModal: FC<IConfigModalProps> = ({
const v = JSON.parse(value)
handlePayloadChange('json_schema')(JSON.stringify(v, null, 2))
} catch {
- return null
+ handlePayloadChange('json_schema')(value)
}
},
[handlePayloadChange],
@@ -120,6 +131,7 @@ const ConfigModal: FC<IConfigModalProps> = ({
const handleTypeChange = useCallback((item: SelectItem) => {
setTempPayload((prev) => createPayloadForType(prev, item.value as InputVarType))
+ setValidationError(undefined)
}, [])
const handleVarKeyBlur = useCallback(
@@ -127,6 +139,7 @@ const ConfigModal: FC<IConfigModalProps> = ({
const varName = e.target.value
if (!checkVariableName(varName, true) || tempPayload.label) return
+ setValidationError((prev) => (prev?.field === 'label' ? undefined : prev))
setTempPayload((prev) => {
return {
...prev,
@@ -159,19 +172,26 @@ const ConfigModal: FC<IConfigModalProps> = ({
)
const handleConfirm = () => {
- const { errorMessage, moreInfo, payloadToSave } = validateConfigModalPayload({
+ const fileUploadConfig = queryClient.getQueryData<FileUploadConfigResponse>(
+ commonQueryKeys.fileUploadConfig,
+ )
+ const { errorMessage, errorField, moreInfo, payloadToSave } = validateConfigModalPayload({
tempPayload,
payload,
- checkVariableName,
+ maxFileUploadLimit: Number(fileUploadConfig?.workflow_file_upload_limit) || undefined,
t,
})
- if (errorMessage) {
+ if (errorMessage && errorField) {
+ setValidationError({ field: errorField, message: errorMessage })
toast.error(errorMessage)
return
}
- if (payloadToSave) onConfirm(payloadToSave, moreInfo)
+ if (payloadToSave) {
+ setValidationError(undefined)
+ onConfirm(payloadToSave, moreInfo)
+ }
}
return (
@@ -182,40 +202,60 @@ const ConfigModal: FC<IConfigModalProps> = ({
}}
>
<DialogContent className="flex max-h-[calc(100dvh-2rem)] flex-col overflow-hidden! border-none p-0! text-left align-middle">
- <DialogTitle className="shrink-0 px-6 pt-6 title-2xl-semi-bold text-text-primary">
- {t(($) => $[`variableConfig.${isCreate ? 'addModalTitle' : 'editModalTitle'}`], {
- ns: 'appDebug',
- })}
- </DialogTitle>
-
- <div
- ref={modalRef}
- tabIndex={-1}
- data-testid="config-modal-scroll-area"
- className="min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto px-6 py-4 pb-8"
+ <form
+ noValidate
+ className="flex min-h-0 flex-col"
+ onSubmit={(event) => {
+ event.preventDefault()
+ handleConfirm()
+ }}
>
- <ConfigModalFormFields
- checkboxDefaultSelectValue={checkboxDefaultSelectValue}
- isStringInput={isStringInput}
- jsonSchemaStr={jsonSchemaStr}
- maxLength={max_length}
- modelId={modelConfig.model_id}
- onFilePayloadChange={(payload) => setTempPayload(payload as InputVar)}
- onJSONSchemaChange={handleJSONSchemaChange}
- onPayloadChange={handlePayloadChange}
- onTypeChange={handleTypeChange}
- onVarKeyBlur={handleVarKeyBlur}
- onVarNameChange={handleVarNameChange}
- options={options}
- selectOptions={selectOptions}
- showHiddenField={showHiddenField}
- tempPayload={tempPayload}
- t={t}
- />
- </div>
- <div className="shrink-0 px-6 pt-2 pb-6">
- <ModalFoot onConfirm={handleConfirm} onCancel={onClose} />
- </div>
+ <DialogTitle className="shrink-0 px-6 pt-6 title-2xl-semi-bold text-text-primary">
+ {t(($) => $[`variableConfig.${isCreate ? 'addModalTitle' : 'editModalTitle'}`], {
+ ns: 'appDebug',
+ })}
+ </DialogTitle>
+
+ <div
+ ref={modalRef}
+ tabIndex={-1}
+ data-testid="config-modal-scroll-area"
+ className="min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto px-6 py-4 pb-8"
+ >
+ <ConfigModalFormFields
+ checkboxDefaultSelectValue={checkboxDefaultSelectValue}
+ isStringInput={isStringInput}
+ jsonSchemaStr={jsonSchemaStr}
+ maxLength={max_length}
+ modelId={modelConfig.model_id}
+ onFilePayloadChange={(nextPayload) => {
+ if (
+ validationError &&
+ (validationError.field === 'allowed_file_types' ||
+ validationError.field === 'allowed_file_extensions') &&
+ (nextPayload[validationError.field] !== tempPayload[validationError.field] ||
+ nextPayload.allowed_file_types !== tempPayload.allowed_file_types)
+ )
+ setValidationError(undefined)
+ setTempPayload(nextPayload as InputVar)
+ }}
+ onJSONSchemaChange={handleJSONSchemaChange}
+ onPayloadChange={handlePayloadChange}
+ onTypeChange={handleTypeChange}
+ onVarKeyBlur={handleVarKeyBlur}
+ onVarNameChange={handleVarNameChange}
+ options={options}
+ selectOptions={selectOptions}
+ showHiddenField={showHiddenField}
+ tempPayload={tempPayload}
+ validationError={validationError}
+ t={t}
+ />
+ </div>
+ <div className="shrink-0 px-6 pt-2 pb-6">
+ <ModalFoot confirmType="submit" onCancel={onClose} />
+ </div>
+ </form>
</DialogContent>
</Dialog>
)
diff --git a/web/app/components/app/configuration/config-var/config-modal/type-select.tsx b/web/app/components/app/configuration/config-var/config-modal/type-select.tsx
index 1d7b96957b4..c1a7b6aa8f9 100644
--- a/web/app/components/app/configuration/config-var/config-modal/type-select.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/type-select.tsx
@@ -7,6 +7,7 @@ import {
SelectItem,
SelectItemIndicator,
SelectItemText,
+ SelectLabel,
SelectList,
SelectPopup,
SelectPortal,
@@ -24,6 +25,8 @@ export type Item = {
}
type Props = Readonly<{
+ label: string
+ labelClassName?: string
value: string | number
onSelect: (value: Item) => void
items: Item[]
@@ -32,7 +35,15 @@ type Props = Readonly<{
readonly?: boolean
hideChecked?: boolean
}>
-const TypeSelector: FC<Props> = ({ value, onSelect, items, popupInnerClassName, readonly }) => {
+const TypeSelector: FC<Props> = ({
+ value,
+ onSelect,
+ items,
+ popupInnerClassName,
+ readonly,
+ label,
+ labelClassName = 'system-sm-semibold leading-8!',
+}) => {
const selectedItem = value ? items.find((item) => item.value === value) : undefined
return (
@@ -44,6 +55,9 @@ const TypeSelector: FC<Props> = ({ value, onSelect, items, popupInnerClassName,
if (selected) onSelect(selected)
}}
>
+ <SelectLabel className={cn('block w-full py-0 text-text-secondary', labelClassName)}>
+ {label}
+ </SelectLabel>
<SelectTrigger
className={cn(
'h-9 rounded-lg px-2 text-sm',
diff --git a/web/app/components/app/configuration/config-var/config-modal/utils.ts b/web/app/components/app/configuration/config-var/config-modal/utils.ts
index e906d05caca..caa90475572 100644
--- a/web/app/components/app/configuration/config-var/config-modal/utils.ts
+++ b/web/app/components/app/configuration/config-var/config-modal/utils.ts
@@ -5,6 +5,7 @@ import { produce } from 'immer'
import { getStringSelectorTranslate } from '@/app/components/app/configuration/utils'
import { DEFAULT_FILE_UPLOAD_SETTING } from '@/app/components/workflow/constants'
import { ChangeType, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { checkKeys } from '@/utils/var'
export const TEXT_MAX_LENGTH = 256
export const CHECKBOX_DEFAULT_TRUE_VALUE = 'true'
@@ -13,14 +14,26 @@ export const CHECKBOX_DEFAULT_FALSE_VALUE = 'false'
type ValidateConfigModalPayloadOptions = {
tempPayload: InputVar
payload?: InputVar
- checkVariableName: (value: string, canBeEmpty?: boolean) => boolean
+ maxFileUploadLimit?: number
t: SelectorTranslate<'appDebug' | 'workflow'>
}
+export type ConfigModalValidationError = {
+ field:
+ | 'variable'
+ | 'label'
+ | 'options'
+ | 'allowed_file_types'
+ | 'allowed_file_extensions'
+ | 'json_schema'
+ message: string
+}
+
type ValidateConfigModalPayloadResult = {
payloadToSave?: InputVar
moreInfo?: MoreInfo
errorMessage?: string
+ errorField?: ConfigModalValidationError['field']
}
export const isStringInputType = (type: InputVarType) =>
@@ -153,14 +166,22 @@ export const buildSelectOptions = ({
export const validateConfigModalPayload = ({
tempPayload,
payload,
- checkVariableName,
+ maxFileUploadLimit,
t: rawTranslate,
}: ValidateConfigModalPayloadOptions): ValidateConfigModalPayloadResult => {
const t = getStringSelectorTranslate(rawTranslate)
const normalizedTempPayload = [InputVarType.singleFile, InputVarType.multiFiles].includes(
tempPayload.type,
)
- ? { ...tempPayload, hide: false }
+ ? {
+ ...tempPayload,
+ hide: false,
+ ...(tempPayload.type === InputVarType.multiFiles && {
+ max_length: Number.isFinite(tempPayload.max_length)
+ ? Math.min(Math.max(tempPayload.max_length!, 1), maxFileUploadLimit ?? Infinity)
+ : 1,
+ }),
+ }
: tempPayload
const jsonSchemaValue = tempPayload.json_schema
const schemaEmpty = isJsonSchemaEmpty(jsonSchemaValue)
@@ -178,10 +199,20 @@ export const validateConfigModalPayload = ({
payload: { beforeKey: payload?.variable || '', afterKey: normalizedTempPayload.variable },
}
- if (!checkVariableName(normalizedTempPayload.variable)) return {}
+ const { isValid, errorMessageKey } = checkKeys([normalizedTempPayload.variable])
+ if (!isValid) {
+ return {
+ errorField: 'variable',
+ errorMessage: t(($) => $[`varKeyError.${errorMessageKey}`], {
+ ns: 'appDebug',
+ key: t(($) => $['variableConfig.varName'], { ns: 'appDebug' }),
+ }),
+ }
+ }
if (!normalizedTempPayload.label) {
return {
+ errorField: 'label',
errorMessage: t(($) => $['variableConfig.errorMsg.labelNameRequired'], { ns: 'appDebug' }),
}
}
@@ -189,6 +220,7 @@ export const validateConfigModalPayload = ({
if (normalizedTempPayload.type === InputVarType.select) {
if (!normalizedTempPayload.options?.length) {
return {
+ errorField: 'options',
errorMessage: t(($) => $['variableConfig.errorMsg.atLeastOneOption'], { ns: 'appDebug' }),
}
}
@@ -203,6 +235,7 @@ export const validateConfigModalPayload = ({
if (hasRepeatedItem) {
return {
+ errorField: 'options',
errorMessage: t(($) => $['variableConfig.errorMsg.optionRepeat'], { ns: 'appDebug' }),
}
}
@@ -211,6 +244,7 @@ export const validateConfigModalPayload = ({
if ([InputVarType.singleFile, InputVarType.multiFiles].includes(normalizedTempPayload.type)) {
if (!normalizedTempPayload.allowed_file_types?.length) {
return {
+ errorField: 'allowed_file_types',
errorMessage: t(($) => $['errorMsg.fieldRequired'], {
ns: 'workflow',
field: t(($) => $['variableConfig.file.supportFileTypes'], { ns: 'appDebug' }),
@@ -223,6 +257,7 @@ export const validateConfigModalPayload = ({
!normalizedTempPayload.allowed_file_extensions?.length
) {
return {
+ errorField: 'allowed_file_extensions',
errorMessage: t(($) => $['errorMsg.fieldRequired'], {
ns: 'workflow',
field: t(($) => $['variableConfig.file.custom.name'], { ns: 'appDebug' }),
@@ -240,6 +275,7 @@ export const validateConfigModalPayload = ({
const schema = JSON.parse(normalizedJsonSchema)
if (schema?.type !== 'object') {
return {
+ errorField: 'json_schema',
errorMessage: t(($) => $['variableConfig.errorMsg.jsonSchemaMustBeObject'], {
ns: 'appDebug',
}),
@@ -247,6 +283,7 @@ export const validateConfigModalPayload = ({
}
} catch {
return {
+ errorField: 'json_schema',
errorMessage: t(($) => $['variableConfig.errorMsg.jsonSchemaInvalid'], { ns: 'appDebug' }),
}
}
diff --git a/web/app/components/app/configuration/config-var/config-select/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-var/config-select/__tests__/index.spec.tsx
index ab536484327..dfe4d0b8c22 100644
--- a/web/app/components/app/configuration/config-var/config-select/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-select/__tests__/index.spec.tsx
@@ -14,7 +14,9 @@ vi.mock('react-sortablejs', () => ({
setList: (list: Array<{ id: number; name: string }>) => void
}) => (
<div>
- <button onClick={() => setList([...list].reverse())}>reorder-options</button>
+ <button type="button" onClick={() => setList([...list].reverse())}>
+ reorder-options
+ </button>
{children}
</div>
),
@@ -30,18 +32,64 @@ describe('ConfigSelect Component', () => {
vi.clearAllMocks()
})
- it('renders all options', () => {
+ it('gives each option input a localized accessible name', () => {
render(<ConfigSelect {...defaultProps} />)
- defaultProps.options.forEach((option) => {
- expect(screen.getByDisplayValue(option)).toBeInTheDocument()
+ defaultProps.options.forEach((option, index) => {
+ expect(
+ screen.getByRole('textbox', {
+ name: `appDebug.variableConfig.options ${index + 1}`,
+ }),
+ ).toHaveValue(option)
})
})
- it('renders add button', () => {
- render(<ConfigSelect {...defaultProps} />)
+ it('associates option errors with the inputs and clears them when corrected', () => {
+ const { rerender } = render(
+ <>
+ <ConfigSelect {...defaultProps} errorMessage="Duplicate options" errorId="options-error" />
+ <p id="options-error">Duplicate options</p>
+ </>,
+ )
+
+ screen.getAllByRole('textbox').forEach((input) => {
+ expect(input).toHaveAttribute('aria-invalid', 'true')
+ expect(input).toHaveAccessibleDescription('Duplicate options')
+ })
+ expect(
+ screen.getByRole('button', {
+ name: 'appDebug.variableConfig.addOption',
+ }),
+ ).not.toHaveAttribute('aria-invalid')
- expect(screen.getByText('appDebug.variableConfig.addOption')).toBeInTheDocument()
+ rerender(<ConfigSelect {...defaultProps} />)
+
+ screen.getAllByRole('textbox').forEach((input) => {
+ expect(input).not.toHaveAttribute('aria-invalid')
+ expect(input).not.toHaveAttribute('aria-describedby')
+ })
+ })
+
+ it('associates the empty-list error with the focusable add action', async () => {
+ const user = userEvent.setup()
+ render(
+ <>
+ <ConfigSelect
+ options={[]}
+ onChange={defaultProps.onChange}
+ errorMessage="Add at least one option"
+ errorId="options-error"
+ />
+ <p id="options-error">Add at least one option</p>
+ </>,
+ )
+
+ const addOption = screen.getByRole('button', { name: 'appDebug.variableConfig.addOption' })
+ await user.tab()
+
+ expect(addOption).toHaveFocus()
+ expect(addOption).toHaveAttribute('aria-invalid', 'true')
+ expect(addOption).toHaveAccessibleDescription('Add at least one option')
})
it('handles option deletion', () => {
@@ -50,14 +98,25 @@ describe('ConfigSelect Component', () => {
expect(defaultProps.onChange).toHaveBeenCalledWith(['Option 2'])
})
- it('handles adding new option', () => {
- render(<ConfigSelect {...defaultProps} />)
- const addButton = screen.getByText('appDebug.variableConfig.addOption')
-
- fireEvent.click(addButton)
-
- expect(defaultProps.onChange).toHaveBeenCalledWith([...defaultProps.options, ''])
- })
+ it.each(['{Enter}', ' '])(
+ 'adds an option with %s without submitting the enclosing form',
+ async (key) => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn((event: React.FormEvent) => event.preventDefault())
+ render(
+ <form onSubmit={onSubmit}>
+ <ConfigSelect options={[]} onChange={defaultProps.onChange} />
+ </form>,
+ )
+ await user.tab()
+ expect(
+ screen.getByRole('button', { name: 'appDebug.variableConfig.addOption' }),
+ ).toHaveFocus()
+ await user.keyboard(key)
+ expect(defaultProps.onChange).toHaveBeenCalledExactlyOnceWith([''])
+ expect(onSubmit).not.toHaveBeenCalled()
+ },
+ )
it('updates option values and clears focus styles on blur', () => {
render(<ConfigSelect {...defaultProps} />)
diff --git a/web/app/components/app/configuration/config-var/config-select/index.tsx b/web/app/components/app/configuration/config-var/config-select/index.tsx
index fc6ec3878af..ea5606005cb 100644
--- a/web/app/components/app/configuration/config-var/config-select/index.tsx
+++ b/web/app/components/app/configuration/config-var/config-select/index.tsx
@@ -1,5 +1,6 @@
'use client'
import type { FC } from 'react'
+import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { RiAddLine, RiDeleteBinLine, RiDraggable } from '@remixicon/react'
@@ -13,9 +14,11 @@ export type Options = string[]
type IConfigSelectProps = {
options: Options
onChange: (options: Options) => void
+ errorMessage?: string
+ errorId?: string
}
-const ConfigSelect: FC<IConfigSelectProps> = ({ options, onChange }) => {
+const ConfigSelect: FC<IConfigSelectProps> = ({ options, onChange, errorMessage, errorId }) => {
const { t } = useTranslation()
const [focusID, setFocusID] = useState<number | null>(null)
const [deletingID, setDeletingID] = useState<number | null>(null)
@@ -64,6 +67,9 @@ const ConfigSelect: FC<IConfigSelectProps> = ({ options, onChange }) => {
<input
key={getItemKey(index)}
type="input"
+ aria-label={`${t(($) => $['variableConfig.options'], { ns: 'appDebug' })} ${index + 1}`}
+ aria-invalid={!!errorMessage || undefined}
+ aria-describedby={errorMessage ? errorId : undefined}
value={o || ''}
onChange={(e) => {
const value = e.target.value
@@ -98,17 +104,21 @@ const ConfigSelect: FC<IConfigSelectProps> = ({ options, onChange }) => {
</div>
)}
- <div
+ <Button
+ type="button"
+ variant="tertiary"
+ aria-invalid={(options.length === 0 && !!errorMessage) || undefined}
+ aria-describedby={options.length === 0 && errorMessage ? errorId : undefined}
onClick={() => {
onChange([...options, ''])
}}
- className="mt-1 flex h-9 cursor-pointer items-center gap-2 rounded-lg bg-components-button-tertiary-bg px-3 text-components-button-tertiary-text hover:bg-components-button-tertiary-bg-hover"
+ className="mt-1 flex h-9 w-full justify-start gap-2 px-3"
>
- <RiAddLine className="size-4" />
- <div className="system-sm-medium text-[13px]">
+ <RiAddLine aria-hidden="true" className="size-4" />
+ <span className="system-sm-medium text-[13px]">
{t(($) => $['variableConfig.addOption'], { ns: 'appDebug' })}
- </div>
- </div>
+ </span>
+ </Button>
</div>
)
}
diff --git a/web/app/components/app/configuration/config-var/config-string/index.tsx b/web/app/components/app/configuration/config-var/config-string/index.tsx
index 82fdcd37c7b..0df71ba1e7c 100644
--- a/web/app/components/app/configuration/config-var/config-string/index.tsx
+++ b/web/app/components/app/configuration/config-var/config-string/index.tsx
@@ -5,13 +5,14 @@ import { useEffect } from 'react'
import Input from '@/app/components/base/input'
export type IConfigStringProps = {
+ id?: string
value: number | undefined
maxLength: number
modelId: string
onChange: (value: number | undefined) => void
}
-const ConfigString: FC<IConfigStringProps> = ({ value, onChange, maxLength }) => {
+const ConfigString: FC<IConfigStringProps> = ({ id, value, onChange, maxLength }) => {
useEffect(() => {
if (value && value > maxLength) onChange(maxLength)
}, [value, maxLength, onChange])
@@ -19,6 +20,7 @@ const ConfigString: FC<IConfigStringProps> = ({ value, onChange, maxLength }) =>
return (
<div>
<Input
+ id={id}
type="number"
max={maxLength}
min={1}
diff --git a/web/app/components/app/configuration/config-var/modal-foot.tsx b/web/app/components/app/configuration/config-var/modal-foot.tsx
index 0c4c45a4d63..0732d4c921d 100644
--- a/web/app/components/app/configuration/config-var/modal-foot.tsx
+++ b/web/app/components/app/configuration/config-var/modal-foot.tsx
@@ -5,16 +5,19 @@ import * as React from 'react'
import { useTranslation } from 'react-i18next'
type IModalFootProps = {
- onConfirm: () => void
+ onConfirm?: () => void
+ confirmType?: 'button' | 'submit'
onCancel: () => void
}
-const ModalFoot: FC<IModalFootProps> = ({ onConfirm, onCancel }) => {
+const ModalFoot: FC<IModalFootProps> = ({ onConfirm, onCancel, confirmType = 'button' }) => {
const { t } = useTranslation()
return (
<div className="flex justify-end gap-2">
- <Button onClick={onCancel}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
- <Button variant="primary" onClick={onConfirm}>
+ <Button type="button" onClick={onCancel}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
+ <Button type={confirmType} variant="primary" onClick={onConfirm}>
{t(($) => $['operation.save'], { ns: 'common' })}
</Button>
</div>
diff --git a/web/app/components/base/checkbox-list/index.tsx b/web/app/components/base/checkbox-list/index.tsx
index 3e246877524..aacb01316c4 100644
--- a/web/app/components/base/checkbox-list/index.tsx
+++ b/web/app/components/base/checkbox-list/index.tsx
@@ -19,6 +19,9 @@ type CheckboxListOption = {
type CheckboxListProps = {
name?: string
+ 'aria-labelledby'?: string
+ 'aria-describedby'?: string
+ 'aria-invalid'?: boolean
title?: string
label?: string
description?: string
@@ -35,6 +38,9 @@ type CheckboxListProps = {
export const CheckboxList = ({
name,
+ 'aria-labelledby': ariaLabelledBy,
+ 'aria-describedby': ariaDescribedBy,
+ 'aria-invalid': ariaInvalid,
title = '',
label,
description,
@@ -73,7 +79,10 @@ export const CheckboxList = ({
<Fieldset
render={
<CheckboxGroup
- aria-label={!label && title ? title : undefined}
+ {...(ariaLabelledBy ? { 'aria-labelledby': ariaLabelledBy } : {})}
+ {...(ariaDescribedBy ? { 'aria-describedby': ariaDescribedBy } : {})}
+ {...(ariaInvalid !== undefined ? { 'aria-invalid': ariaInvalid } : {})}
+ aria-label={!ariaLabelledBy && !label && title ? title : undefined}
value={value}
onValueChange={(nextValue) => onChange?.(nextValue)}
allValues={selectableOptionValues}
diff --git a/web/app/components/base/form/components/base/__tests__/base-field.spec.tsx b/web/app/components/base/form/components/base/__tests__/base-field.spec.tsx
index dae522995f2..169fb6f6d56 100644
--- a/web/app/components/base/form/components/base/__tests__/base-field.spec.tsx
+++ b/web/app/components/base/form/components/base/__tests__/base-field.spec.tsx
@@ -74,6 +74,83 @@ describe('BaseField', () => {
})
})
+ it.each([FormTypeEnum.textInput, FormTypeEnum.secretInput, FormTypeEnum.textNumber])(
+ 'associates the visible label, description and required state for %s',
+ async (type) => {
+ const user = userEvent.setup()
+ renderBaseField({
+ formSchema: {
+ type,
+ name: 'credential',
+ label: 'Credential',
+ description: 'Use the workspace credential',
+ required: true,
+ options: [{ label: 'Primary', value: 'primary' }],
+ },
+ })
+ const control = screen.getByLabelText('Credential')
+ expect(control).toHaveAccessibleName('Credential')
+ expect(control).toHaveAccessibleDescription('Use the workspace credential')
+ expect(control).toBeRequired()
+ await user.click(screen.getByText('Credential'))
+ expect(control).toHaveFocus()
+ },
+ )
+
+ it.each([
+ { type: FormTypeEnum.select, multiple: false },
+ { type: FormTypeEnum.select, multiple: true },
+ { type: FormTypeEnum.dynamicSelect, multiple: false },
+ { type: FormTypeEnum.dynamicSelect, multiple: true },
+ ])(
+ 'focuses the $type trigger from its label and supports keyboard selection (multiple: $multiple)',
+ async ({ type, multiple }) => {
+ const user = userEvent.setup()
+ const options = [{ label: 'Primary', value: 'primary' }]
+ mockDynamicOptions.mockReturnValue({
+ data: { options },
+ isLoading: false,
+ error: null,
+ })
+ renderBaseField({
+ formSchema: {
+ type,
+ multiple,
+ name: 'credential',
+ label: 'Credential',
+ description: 'Use the workspace credential',
+ tooltip: 'Credential help',
+ required: true,
+ options,
+ },
+ defaultValues: { credential: multiple ? [] : '' },
+ fieldState: {
+ validateStatus: FormItemValidateStatusEnum.Error,
+ errors: ['Choose a credential'],
+ },
+ showCurrentValue: true,
+ })
+
+ const control = screen.getByRole('combobox', { name: 'Credential' })
+ expect(control).toHaveAccessibleDescription(
+ 'Use the workspace credential Choose a credential',
+ )
+ expect(control).toBeInvalid()
+ expect(control).toBeRequired()
+ expect(screen.getByRole('button', { name: 'Credential help' })).toBeInTheDocument()
+ await user.click(screen.getByText('Credential'))
+ expect(control).toHaveFocus()
+ expect(control).toHaveAttribute('aria-expanded', 'false')
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
+
+ await user.keyboard('{ArrowDown}')
+ expect(control).toHaveAttribute('aria-expanded', 'true')
+ expect(screen.getByRole('option', { name: 'Primary' })).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(screen.getByTestId('field-value')).toHaveTextContent('primary')
+ },
+ )
+
it('should render text input and propagate changes', async () => {
const onChange = vi.fn()
renderBaseField({
@@ -188,6 +265,31 @@ describe('BaseField', () => {
expect(onChange).toHaveBeenCalledWith('visibility', 'private')
})
+ it.each([
+ { type: FormTypeEnum.select, role: 'combobox' },
+ { type: FormTypeEnum.radio, role: 'radiogroup' },
+ { type: FormTypeEnum.checkbox, role: 'group' },
+ ])('associates $type validation and description with the named control', ({ type, role }) => {
+ renderBaseField({
+ formSchema: {
+ type,
+ name: 'access',
+ label: 'Access level',
+ description: 'Choose an access level',
+ required: true,
+ options: [{ label: 'Public', value: 'public' }],
+ },
+ defaultValues: { access: type === FormTypeEnum.checkbox ? [] : '' },
+ fieldState: {
+ validateStatus: FormItemValidateStatusEnum.Error,
+ errors: ['Choose an option'],
+ },
+ })
+ const control = screen.getByRole(role, { name: 'Access level' })
+ expect(control).toHaveAttribute('aria-invalid', 'true')
+ expect(control).toHaveAccessibleDescription('Choose an access level Choose an option')
+ })
+
it('should show validation message when field state has an error', () => {
renderBaseField({
formSchema: {
@@ -202,7 +304,9 @@ describe('BaseField', () => {
},
})
- expect(screen.getByText('Name is required')).toBeInTheDocument()
+ const input = screen.getByRole('textbox', { name: 'Name' })
+ expect(input).toBeInvalid()
+ expect(input).toHaveAccessibleDescription('Name is required')
})
it('should render description and help link when provided', () => {
diff --git a/web/app/components/base/form/components/base/__tests__/validation-accessibility.spec.tsx b/web/app/components/base/form/components/base/__tests__/validation-accessibility.spec.tsx
new file mode 100644
index 00000000000..175889b5d38
--- /dev/null
+++ b/web/app/components/base/form/components/base/__tests__/validation-accessibility.spec.tsx
@@ -0,0 +1,121 @@
+import type { FormRefObject, FormSchema } from '@/app/components/base/form/types'
+import { act, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { createRef } from 'react'
+import { FormTypeEnum } from '@/app/components/base/form/types'
+import BaseForm from '../base-form'
+
+vi.mock('@/hooks/use-i18n', () => ({
+ useRenderI18nObject: () => (content: Record<string, string>) => content.en_US ?? '',
+}))
+
+vi.mock('@/service/use-triggers', () => ({
+ useTriggerPluginDynamicOptions: () => ({ data: undefined, isLoading: false, error: null }),
+}))
+
+vi.mock('@langgenius/dify-ui/toast', () => ({ toast: { error: vi.fn() } }))
+
+const requiredSchema = (label: string): FormSchema => ({
+ name: 'token',
+ label,
+ type: FormTypeEnum.secretInput,
+ required: true,
+ description: 'Paste your API token',
+ tooltip: 'Find this token in the provider settings',
+ validators: {
+ onMount: ({ value }: { value: unknown }) => (!value ? 'Token is required' : undefined),
+ onChange: ({ value }: { value: unknown }) => (!value ? 'Token is required' : undefined),
+ },
+})
+
+describe('BaseForm validation accessibility', () => {
+ it('shows client validation again after editing clears a server error', async () => {
+ const user = userEvent.setup()
+ const ref = createRef<FormRefObject>()
+ render(
+ <>
+ <BaseForm
+ ref={ref}
+ formSchemas={[requiredSchema('API token')]}
+ onChange={(name) => ref.current?.setFields([{ name, errors: [] }])}
+ />
+ <button type="button" onClick={() => ref.current?.getFormValues({})}>
+ Save credentials
+ </button>
+ </>,
+ )
+ const input = screen.getByLabelText('API token')
+ await user.type(input, 'rejected-token')
+ act(() => {
+ ref.current?.setFields([{ name: 'token', errors: ['Token was rejected'] }])
+ })
+ expect(input).toBeInvalid()
+ expect(input).toHaveAccessibleDescription('Paste your API token Token was rejected')
+
+ await user.clear(input)
+ await user.click(screen.getByRole('button', { name: 'Save credentials' }))
+ expect(input).toHaveFocus()
+ expect(input).toBeInvalid()
+ expect(input).toHaveAccessibleDescription('Paste your API token Token is required')
+ expect(screen.queryByText('Token was rejected')).not.toBeInTheDocument()
+
+ await user.type(input, 'valid-token')
+ expect(input).not.toBeInvalid()
+ expect(input).toHaveAccessibleDescription('Paste your API token')
+ expect(screen.queryByText('Token is required')).not.toBeInTheDocument()
+ })
+
+ it('focuses the invalid field in the submitting form and associates the error until corrected', async () => {
+ const user = userEvent.setup()
+ const ref = createRef<FormRefObject>()
+ render(
+ <>
+ <BaseForm formSchemas={[requiredSchema('Other token')]} />
+ <BaseForm ref={ref} formSchemas={[requiredSchema('API token')]} />
+ <button type="button" onClick={() => ref.current?.getFormValues({})}>
+ Save credentials
+ </button>
+ </>,
+ )
+ const input = screen.getByLabelText('API token')
+ expect(input).not.toBeInvalid()
+ await user.click(screen.getByRole('button', { name: 'Save credentials' }))
+ expect(input).toHaveFocus()
+ expect(input).toBeInvalid()
+ expect(input).toHaveAccessibleDescription('Paste your API token Token is required')
+ expect(screen.getByLabelText('Other token')).not.toBeInvalid()
+
+ await user.type(input, 'valid-token')
+ expect(input).not.toBeInvalid()
+ expect(input).toHaveAccessibleDescription('Paste your API token')
+ expect(screen.queryByText('Token is required')).not.toBeInTheDocument()
+ })
+
+ it('skips hidden field errors and focuses the first visible invalid field in schema order', async () => {
+ const user = userEvent.setup()
+ const ref = createRef<FormRefObject>()
+ render(
+ <>
+ <BaseForm
+ ref={ref}
+ defaultValues={{ enabled: 'no' }}
+ formSchemas={[
+ {
+ ...requiredSchema('Hidden token'),
+ name: 'hidden',
+ show_on: [{ variable: 'enabled', value: 'yes' }],
+ },
+ requiredSchema('Visible token'),
+ { ...requiredSchema('Later token'), name: 'later' },
+ ]}
+ />
+ <button type="button" onClick={() => ref.current?.getFormValues({})}>
+ Save credentials
+ </button>
+ </>,
+ )
+ await user.click(screen.getByRole('button', { name: 'Save credentials' }))
+ expect(screen.getByLabelText('Visible token')).toHaveFocus()
+ expect(screen.queryByLabelText('Hidden token')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/base/form/components/base/base-field.tsx b/web/app/components/base/form/components/base/base-field.tsx
index 145e479a475..7d847bfe4b4 100644
--- a/web/app/components/base/form/components/base/base-field.tsx
+++ b/web/app/components/base/form/components/base/base-field.tsx
@@ -10,11 +10,12 @@ import {
SelectItem,
SelectItemIndicator,
SelectItemText,
+ SelectLabel,
SelectTrigger,
SelectValue,
} from '@langgenius/dify-ui/select'
import { useStore } from '@tanstack/react-form'
-import { isValidElement, memo, useCallback, useMemo } from 'react'
+import { isValidElement, memo, useCallback, useId, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { CheckboxList } from '@/app/components/base/checkbox-list'
import { FormItemValidateStatusEnum, FormTypeEnum } from '@/app/components/base/form/types'
@@ -143,6 +144,36 @@ const BaseField = ({
help,
} = formSchema
const disabled = propsDisabled || formSchemaDisabled
+ const controlId = useId()
+ const labelId = `${controlId}-label`
+ const descriptionId = `${controlId}-description`
+ const messageId = `${controlId}-message`
+ const meta = useStore(field.form.store, (state) => state.fieldMeta[field.name])
+ // Nonempty external errors take priority; clearing them restores client validation.
+ const errors = fieldState?.errors?.length ? fieldState.errors : meta?.isTouched ? meta.errors : []
+ const validateStatus =
+ fieldState?.validateStatus ?? (errors?.length ? FormItemValidateStatusEnum.Error : undefined)
+ const messages =
+ validateStatus === FormItemValidateStatusEnum.Error
+ ? errors
+ : validateStatus === FormItemValidateStatusEnum.Warning
+ ? fieldState?.warnings
+ : undefined
+ const hasMessage = !!messages?.length
+ const controlProps = {
+ 'aria-describedby':
+ [description && descriptionId, hasMessage && messageId].filter(Boolean).join(' ') ||
+ undefined,
+ 'aria-invalid': validateStatus === FormItemValidateStatusEnum.Error || undefined,
+ 'aria-required': required || undefined,
+ }
+ const isDynamicSelect = formItemType === FormTypeEnum.dynamicSelect
+ const isSelect = formItemType === FormTypeEnum.select || isDynamicSelect
+ const isSingleControl = [
+ FormTypeEnum.textInput,
+ FormTypeEnum.secretInput,
+ FormTypeEnum.textNumber,
+ ].includes(formItemType)
const [
translatedLabel,
@@ -238,13 +269,30 @@ const BaseField = ({
: null
const dynamicNoticeClassName = dynamicOptionsError ? 'text-text-destructive-secondary' : undefined
- return (
+ const selectOptions = isDynamicSelect ? dynamicOptions : memorizedOptions
+ const selectPlaceholder = isDynamicSelect ? dynamicPlaceholder : translatedPlaceholder
+ const handleSelectChange = isDynamicSelect ? field.handleChange : handleChange
+ const selectDisabled = disabled || (isDynamicSelect && isDynamicOptionsLoading)
+
+ const content = (
<>
<div className={cn(fieldClassName)}>
<div className={cn(labelClassName, formLabelClassName)}>
- {translatedLabel}
+ {isSelect ? (
+ <SelectLabel className="inline p-0 text-inherit [font:inherit]">
+ {translatedLabel || name}
+ </SelectLabel>
+ ) : isSingleControl ? (
+ <label id={labelId} htmlFor={controlId}>
+ {translatedLabel || name}
+ </label>
+ ) : (
+ <span id={labelId}>{translatedLabel || name}</span>
+ )}
{required && !isValidElement(label) && (
- <span className="ml-1 text-text-destructive-secondary">*</span>
+ <span aria-hidden="true" className="ml-1 text-text-destructive-secondary">
+ *
+ </span>
)}
{translatedTooltip && (
<Infotip aria-label={translatedTooltip} className="ml-0.5" popupClassName="w-[200px]">
@@ -252,16 +300,17 @@ const BaseField = ({
</Infotip>
)}
</div>
- <div className={cn(inputContainerClassName)}>
+ <div className={cn(inputContainerClassName)} data-form-field={field.name}>
{[FormTypeEnum.textInput, FormTypeEnum.secretInput, FormTypeEnum.textNumber].includes(
formItemType,
) && (
<Input
- id={field.name}
+ id={controlId}
name={field.name}
+ {...controlProps}
className={cn(
inputClassName,
- VALIDATE_STATUS_STYLE_MAP[fieldState?.validateStatus as FormItemValidateStatusEnum]
+ VALIDATE_STATUS_STYLE_MAP[validateStatus as FormItemValidateStatusEnum]
?.componentClassName,
)}
value={value || ''}
@@ -275,73 +324,54 @@ const BaseField = ({
showCopyIcon={showCopy}
/>
)}
- {formItemType === FormTypeEnum.select &&
- (multiple ? (
- <Select<string, true>
- 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<string, true> placeholder={translatedPlaceholder}>
+ {isSelect && (
+ <>
+ <SelectTrigger id={controlId} {...controlProps} className="px-2">
+ {multiple ? (
+ <SelectValue<string, true> placeholder={selectPlaceholder}>
{(selectedValue) =>
selectedValue?.length
? t(($) => $['dynamicSelect.selected'], {
ns: 'common',
count: selectedValue.length,
})
- : translatedPlaceholder
+ : selectPlaceholder
}
</SelectValue>
- </SelectTrigger>
- <SelectContent className="max-h-80 bg-components-panel-bg-blur">
- {memorizedOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- <SelectItemText>{option.label}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- ) : (
- <Select<string>
- 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<string> placeholder={translatedPlaceholder}>
+ ) : (
+ <SelectValue<string> placeholder={selectPlaceholder}>
{(nextValue) =>
- getSingleSelectLabel(nextValue, memorizedOptions, translatedPlaceholder)
+ getSingleSelectLabel(nextValue, selectOptions, selectPlaceholder)
}
</SelectValue>
- </SelectTrigger>
- <SelectContent className="max-h-80 bg-components-panel-bg-blur">
- {memorizedOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- <SelectItemText>{option.label}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- ))}
+ )}
+ </SelectTrigger>
+ <SelectContent
+ className={cn('bg-components-panel-bg-blur', !isDynamicSelect && 'max-h-80')}
+ >
+ {isDynamicSelect && dynamicNoticeTitle && (
+ <div
+ className={cn(
+ 'flex h-5.5 items-center px-3 system-xs-medium-uppercase text-text-tertiary',
+ dynamicNoticeClassName,
+ )}
+ >
+ {dynamicNoticeTitle}
+ </div>
+ )}
+ {selectOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ <SelectItemText>{option.label}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </>
+ )}
{formItemType === FormTypeEnum.checkbox /* && multiple */ && (
<CheckboxList
+ {...controlProps}
+ aria-labelledby={labelId}
name={field.name}
title={name}
value={value}
@@ -350,96 +380,13 @@ const BaseField = ({
maxHeight="200px"
/>
)}
- {formItemType === FormTypeEnum.dynamicSelect &&
- (multiple ? (
- <Select<string, true>
- 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<string, true> placeholder={dynamicPlaceholder}>
- {(selectedValue) =>
- selectedValue?.length
- ? t(($) => $['dynamicSelect.selected'], {
- ns: 'common',
- count: selectedValue.length,
- })
- : dynamicPlaceholder
- }
- </SelectValue>
- </SelectTrigger>
- <SelectContent className="bg-components-panel-bg-blur">
- {dynamicNoticeTitle && (
- <div
- className={cn(
- 'flex h-5.5 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<string>
- 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<string> placeholder={dynamicPlaceholder}>
- {(nextValue) =>
- getSingleSelectLabel(nextValue, dynamicOptions, dynamicPlaceholder)
- }
- </SelectValue>
- </SelectTrigger>
- <SelectContent className="bg-components-panel-bg-blur">
- {dynamicNoticeTitle && (
- <div
- className={cn(
- 'flex h-5.5 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 && (
<Field name={name} className="contents">
<Fieldset
render={
<RadioGroup
+ {...controlProps}
+ aria-labelledby={labelId}
value={stringValue}
onValueChange={(optionValue) => handleChange(optionValue)}
className={cn(memorizedOptions.length >= 3 && 'flex-col items-stretch')}
@@ -454,7 +401,7 @@ const BaseField = ({
>
<FieldLabel
className={cn(
- 'hover:bg-components-option-card-option-hover-bg hover:border-components-option-card-option-hover-border flex h-8 w-full cursor-pointer items-center justify-center gap-2 rounded-lg border border-components-option-card-option-border bg-components-option-card-option-bg p-2 system-sm-regular text-text-secondary',
+ 'hover:bg-components-option-card-option-hover-bg hover:border-components-option-card-option-hover-border flex h-8 w-full cursor-pointer items-center justify-center gap-2 rounded-lg border border-components-option-card-option-border bg-components-option-card-option-bg p-2 system-sm-regular text-text-secondary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-components-input-border-active',
value === option.value &&
'border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg text-text-primary shadow-xs',
disabled && 'cursor-not-allowed opacity-50',
@@ -479,6 +426,8 @@ const BaseField = ({
<Fieldset
render={
<RadioGroup<boolean>
+ {...controlProps}
+ aria-labelledby={labelId}
className="w-fit gap-3"
value={booleanValue}
onValueChange={(v) => field.handleChange(v)}
@@ -501,28 +450,25 @@ const BaseField = ({
</Fieldset>
</Field>
)}
- {fieldState?.validateStatus &&
- [FormItemValidateStatusEnum.Error, FormItemValidateStatusEnum.Warning].includes(
- fieldState?.validateStatus,
- ) && (
- <div
- className={cn(
- 'mt-1 px-0 py-0.5 system-xs-regular',
- VALIDATE_STATUS_STYLE_MAP[fieldState?.validateStatus].textClassName,
- )}
- >
- {
- fieldState?.[
- VALIDATE_STATUS_STYLE_MAP[fieldState?.validateStatus]
- .infoFieldName as keyof FieldState
- ]
- }
- </div>
- )}
+ {hasMessage && (
+ <div
+ id={messageId}
+ className={cn(
+ 'mt-1 px-0 py-0.5 system-xs-regular',
+ VALIDATE_STATUS_STYLE_MAP[validateStatus!].textClassName,
+ )}
+ >
+ {messages
+ .map((message) => (typeof message === 'string' ? message : message.message))
+ .join(' ')}
+ </div>
+ )}
</div>
</div>
{description && (
- <div className="mt-4 system-xs-regular text-text-tertiary">{translatedDescription}</div>
+ <div id={descriptionId} className="mt-4 system-xs-regular text-text-tertiary">
+ {translatedDescription}
+ </div>
)}
{url && (
<a
@@ -536,6 +482,32 @@ const BaseField = ({
)}
</>
)
+
+ if (!isSelect) return content
+
+ return multiple ? (
+ <Select<string, true>
+ multiple
+ items={selectOptions}
+ value={Array.isArray(value) ? value : []}
+ disabled={selectDisabled}
+ onValueChange={handleSelectChange}
+ >
+ {content}
+ </Select>
+ ) : (
+ <Select<string>
+ items={selectOptions}
+ value={getSingleSelectValue(value, selectOptions)}
+ disabled={selectDisabled}
+ onValueChange={(next) => {
+ if (next == null) return
+ handleSelectChange(next)
+ }}
+ >
+ {content}
+ </Select>
+ )
}
export default memo(BaseField)
diff --git a/web/app/components/base/form/components/base/base-form.tsx b/web/app/components/base/form/components/base/base-form.tsx
index 22122f8aeb3..26cddf724b4 100644
--- a/web/app/components/base/form/components/base/base-form.tsx
+++ b/web/app/components/base/form/components/base/base-form.tsx
@@ -8,7 +8,7 @@ import type {
} from '@/app/components/base/form/types'
import { cn } from '@langgenius/dify-ui/cn'
import { useForm, useStore } from '@tanstack/react-form'
-import { memo, useCallback, useImperativeHandle, useMemo, useState } from 'react'
+import { memo, useCallback, useImperativeHandle, useMemo, useRef, useState } from 'react'
import { useGetFormValues, useGetValidators } from '@/app/components/base/form/hooks'
import { FormItemValidateStatusEnum } from '@/app/components/base/form/types'
import { BaseField } from '.'
@@ -58,7 +58,25 @@ const BaseForm = ({
defaultValues: initialDefaultValues,
})
const form: any = formFromProps || formFromHook
- const { getFormValues } = useGetFormValues(form, formSchemas)
+ const formElementRef = useRef<HTMLFormElement>(null)
+ const focusInvalidField = useCallback(
+ (name: string) => {
+ form.setFieldMeta(name, (meta: AnyFieldApi['state']['meta']) => ({
+ ...meta,
+ isTouched: true,
+ }))
+ const fieldElement = Array.from(
+ formElementRef.current?.querySelectorAll<HTMLElement>('[data-form-field]') ?? [],
+ ).find((element) => element.dataset.formField === name)
+ fieldElement
+ ?.querySelector<HTMLElement>(
+ 'input:not([type="hidden"]):not(:disabled), button:not(:disabled), textarea:not(:disabled), [role="checkbox"]:not([aria-disabled="true"]), [role="radio"]:not([aria-disabled="true"])',
+ )
+ ?.focus()
+ },
+ [form],
+ )
+ const { getFormValues } = useGetFormValues(form, formSchemas, focusInvalidField)
const { getValidators } = useGetValidators()
const [fieldStates, setFieldStates] = useState<Record<string, FieldState>>({})
@@ -183,7 +201,7 @@ const BaseForm = ({
}
return (
- <form className={cn(formClassName)} onSubmit={handleSubmit}>
+ <form ref={formElementRef} className={cn(formClassName)} onSubmit={handleSubmit}>
{formSchemas.map(renderFieldWrapper)}
</form>
)
diff --git a/web/app/components/base/form/components/field/__tests__/upload-method.spec.tsx b/web/app/components/base/form/components/field/__tests__/upload-method.spec.tsx
index 0aca2500902..8da9e23223b 100644
--- a/web/app/components/base/form/components/field/__tests__/upload-method.spec.tsx
+++ b/web/app/components/base/form/components/field/__tests__/upload-method.spec.tsx
@@ -1,66 +1,56 @@
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { TransferMethod } from '@/types/app'
-import UploadMethodField from '../upload-method'
+import { useAppForm } from '../../..'
-const mockField = {
- name: 'upload-method',
- state: {
- value: [TransferMethod.local_file] as TransferMethod[],
- },
- handleChange: vi.fn(),
-}
-
-vi.mock('../../..', () => ({
- useFieldContext: () => mockField,
-}))
-
-vi.mock('@/app/components/workflow/nodes/_base/components/option-card', () => ({
- default: ({
- title,
- selected,
- onSelect,
- }: {
- title: string
- selected: boolean
- onSelect: () => void
- }) => (
- <button aria-pressed={selected} onClick={onSelect}>
- {title}
- </button>
- ),
-}))
-
-describe('UploadMethodField', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockField.state.value = [TransferMethod.local_file]
+const UploadMethodForm = ({ onSubmit }: { onSubmit: (value: TransferMethod[]) => void }) => {
+ const form = useAppForm({
+ defaultValues: { methods: [TransferMethod.local_file] as TransferMethod[] },
+ onSubmit: ({ value }) => onSubmit(value.methods),
})
- it('should show all upload method options', () => {
- render(<UploadMethodField label="Upload methods" />)
-
- expect(screen.getByText('Upload methods')).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'appDebug.variableConfig.localUpload' }),
- ).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'URL' })).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'appDebug.variableConfig.both' })).toBeInTheDocument()
- })
-
- it('should switch to URL-only when users select URL', () => {
- render(<UploadMethodField label="Upload methods" />)
+ return (
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ void form.handleSubmit()
+ }}
+ >
+ <form.AppField name="methods">
+ {(field) => <field.UploadMethodField label="Upload methods" />}
+ </form.AppField>
+ <button type="submit">Save</button>
+ </form>
+ )
+}
- fireEvent.click(screen.getByRole('button', { name: 'URL' }))
- expect(mockField.handleChange).toHaveBeenCalledWith([TransferMethod.remote_url])
+describe('UploadMethodField', () => {
+ it('lets keyboard users choose both methods and saves the existing array representation', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn()
+ render(<UploadMethodForm onSubmit={onSubmit} />)
+
+ expect(screen.getByRole('radiogroup', { name: 'Upload methods' })).toBeInTheDocument()
+ await user.tab()
+ expect(screen.getByRole('radio', { name: 'appDebug.variableConfig.localUpload' })).toHaveFocus()
+ await user.keyboard('{ArrowRight}')
+ expect(screen.getByRole('radio', { name: 'URL' })).toBeChecked()
+ await user.keyboard('{ArrowRight}')
+ expect(screen.getByRole('radio', { name: 'appDebug.variableConfig.both' })).toBeChecked()
+ await user.tab()
+ expect(screen.getByRole('button', { name: 'Save' })).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(onSubmit).toHaveBeenCalledWith([TransferMethod.local_file, TransferMethod.remote_url])
})
- it('should enable both methods when users select both', () => {
- render(<UploadMethodField label="Upload methods" />)
+ it('lets users select a card by its visible label and saves only URL upload', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn()
+ render(<UploadMethodForm onSubmit={onSubmit} />)
- fireEvent.click(screen.getByRole('button', { name: 'appDebug.variableConfig.both' }))
- expect(mockField.handleChange).toHaveBeenCalledWith([
- TransferMethod.local_file,
- TransferMethod.remote_url,
- ])
+ await user.click(screen.getByText('URL'))
+ expect(screen.getByRole('radio', { name: 'URL' })).toBeChecked()
+ await user.click(screen.getByRole('button', { name: 'Save' }))
+ expect(onSubmit).toHaveBeenCalledWith([TransferMethod.remote_url])
})
})
diff --git a/web/app/components/base/form/components/field/upload-method.tsx b/web/app/components/base/form/components/field/upload-method.tsx
index e6419ffbb10..fa2c102f5b9 100644
--- a/web/app/components/base/form/components/field/upload-method.tsx
+++ b/web/app/components/base/form/components/field/upload-method.tsx
@@ -1,11 +1,13 @@
import type { LabelProps } from '../label'
import { cn } from '@langgenius/dify-ui/cn'
+import { Field, FieldItem, FieldLabel } from '@langgenius/dify-ui/field'
+import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
+import { RadioGroup, RadioItem } from '@langgenius/dify-ui/radio-group'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
-import OptionCard from '@/app/components/workflow/nodes/_base/components/option-card'
+import { Infotip } from '@/app/components/base/infotip'
import { TransferMethod } from '@/types/app'
import { useFieldContext } from '../..'
-import Label from '../label'
type UploadMethodFieldProps = {
label: string
@@ -30,29 +32,75 @@ const UploadMethodField = ({ label, labelOptions, className }: UploadMethodField
[field],
)
+ const selectedMethod = value.includes(TransferMethod.local_file)
+ ? value.includes(TransferMethod.remote_url)
+ ? TransferMethod.all
+ : TransferMethod.local_file
+ : value.includes(TransferMethod.remote_url)
+ ? TransferMethod.remote_url
+ : undefined
+ const options = [
+ {
+ value: TransferMethod.local_file,
+ label: t(($) => $['variableConfig.localUpload'], { ns: 'appDebug' }),
+ },
+ { value: TransferMethod.remote_url, label: 'URL' },
+ { value: TransferMethod.all, label: t(($) => $['variableConfig.both'], { ns: 'appDebug' }) },
+ ]
+
return (
- <div className={cn('flex flex-col gap-y-0.5', className)}>
- <Label htmlFor={field.name} label={label} {...(labelOptions ?? {})} />
- <div className="grid grid-cols-3 gap-2">
- <OptionCard
- title={t(($) => $['variableConfig.localUpload'], { ns: 'appDebug' })}
- selected={value.length === 1 && value.includes(TransferMethod.local_file)}
- onSelect={handleUploadMethodChange.bind(null, TransferMethod.local_file)}
- />
- <OptionCard
- title="URL"
- selected={value.length === 1 && value.includes(TransferMethod.remote_url)}
- onSelect={handleUploadMethodChange.bind(null, TransferMethod.remote_url)}
- />
- <OptionCard
- title={t(($) => $['variableConfig.both'], { ns: 'appDebug' })}
- selected={
- value.includes(TransferMethod.local_file) && value.includes(TransferMethod.remote_url)
- }
- onSelect={handleUploadMethodChange.bind(null, TransferMethod.all)}
- />
- </div>
- </div>
+ <Field name={field.name} className={className}>
+ <Fieldset
+ className="flex flex-col items-stretch gap-y-0.5"
+ render={
+ <RadioGroup<TransferMethod>
+ value={selectedMethod}
+ onValueChange={handleUploadMethodChange}
+ />
+ }
+ >
+ <div className="flex h-6 items-center">
+ <FieldsetLegend className={cn('mb-0 py-0', labelOptions?.className)}>
+ {label}
+ </FieldsetLegend>
+ {!labelOptions?.isRequired && labelOptions?.showOptional && (
+ <span className="ml-1 system-xs-regular text-text-tertiary">
+ {t(($) => $['label.optional'], { ns: 'common' })}
+ </span>
+ )}
+ {labelOptions?.isRequired && (
+ <span className="ml-1 system-xs-regular text-text-destructive-secondary">*</span>
+ )}
+ {labelOptions?.tooltip && (
+ <Infotip
+ aria-label={labelOptions.tooltip}
+ className="ml-0.5 size-4"
+ popupClassName="w-[200px]"
+ >
+ {labelOptions.tooltip}
+ </Infotip>
+ )}
+ </div>
+ <div className="grid grid-cols-3 gap-2">
+ {options.map((option) => (
+ <FieldItem key={option.value}>
+ <FieldLabel className="block w-full min-w-0 py-0">
+ <RadioItem<TransferMethod>
+ value={option.value}
+ className={cn(
+ 'flex h-8 w-full cursor-default items-center justify-center rounded-md border border-components-option-card-option-border bg-components-option-card-option-bg px-2 system-sm-regular text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-checked:border-[1.5px] data-checked:border-components-option-card-option-selected-border data-checked:bg-components-option-card-option-selected-bg data-checked:shadow-xs',
+ selectedMethod !== option.value &&
+ 'cursor-pointer hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',
+ )}
+ >
+ <span>{option.label}</span>
+ </RadioItem>
+ </FieldLabel>
+ </FieldItem>
+ ))}
+ </div>
+ </Fieldset>
+ </Field>
)
}
diff --git a/web/app/components/base/form/hooks/use-check-validated.ts b/web/app/components/base/form/hooks/use-check-validated.ts
index 6aa59df1126..d7ca22616b0 100644
--- a/web/app/components/base/form/hooks/use-check-validated.ts
+++ b/web/app/components/base/form/hooks/use-check-validated.ts
@@ -3,13 +3,21 @@ import type { FormSchema } from '@/app/components/base/form/types'
import { toast } from '@langgenius/dify-ui/toast'
import { useCallback } from 'react'
-export const useCheckValidated = (form: AnyFormApi, FormSchemas: FormSchema[]) => {
+export const useCheckValidated = (
+ form: AnyFormApi,
+ FormSchemas: FormSchema[],
+ onInvalidField?: (name: string) => void,
+) => {
const checkValidated = useCallback(() => {
const allError = form?.getAllErrors()
const values = form.state.values
if (allError) {
const fields = allError.fields
- const errorArray = Object.keys(fields).reduce((acc: string[], key: string) => {
+ let firstInvalidField: string | undefined
+ const fieldNames = [
+ ...new Set([...FormSchemas.map((schema) => schema.name), ...Object.keys(fields)]),
+ ]
+ const errorArray = fieldNames.reduce((acc: string[], key: string) => {
const currentSchema = FormSchemas.find((schema) => schema.name === key)
const { show_on = [] } = currentSchema || {}
const showOnValues = show_on.reduce(
@@ -23,17 +31,19 @@ export const useCheckValidated = (form: AnyFormApi, FormSchemas: FormSchema[]) =
const conditionValue = showOnValues[condition.variable]
return conditionValue === condition.value
})
- const errors: any[] = show ? fields[key]!.errors : []
+ const errors: any[] = show ? (fields[key]?.errors ?? []) : []
+ if (errors.length && firstInvalidField === undefined) firstInvalidField = key
return [...acc, ...errors]
}, [] as string[])
if (errorArray.length) {
toast.error(errorArray[0])
+ if (firstInvalidField !== undefined) onInvalidField?.(firstInvalidField)
return false
}
return true
}
return true
- }, [form, FormSchemas])
+ }, [form, FormSchemas, onInvalidField])
return {
checkValidated,
}
diff --git a/web/app/components/base/form/hooks/use-get-form-values.ts b/web/app/components/base/form/hooks/use-get-form-values.ts
index 6fca75f7ff1..282e53fd781 100644
--- a/web/app/components/base/form/hooks/use-get-form-values.ts
+++ b/web/app/components/base/form/hooks/use-get-form-values.ts
@@ -4,8 +4,12 @@ import { useCallback } from 'react'
import { getTransformedValuesWhenSecretInputPristine } from '../utils/secret-input'
import { useCheckValidated } from './use-check-validated'
-export const useGetFormValues = (form: AnyFormApi, formSchemas: FormSchema[]) => {
- const { checkValidated } = useCheckValidated(form, formSchemas)
+export const useGetFormValues = (
+ form: AnyFormApi,
+ formSchemas: FormSchema[],
+ onInvalidField?: (name: string) => void,
+) => {
+ const { checkValidated } = useCheckValidated(form, formSchemas, onInvalidField)
const getFormValues = useCallback(
({
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx
index 141b414af5f..a3ddd76d67f 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx
@@ -27,26 +27,6 @@ vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference
},
}))
-vi.mock('@/app/components/app/configuration/config-var/config-modal/type-select', () => ({
- __esModule: true,
- default: ({ onSelect }: { onSelect: (item: { value: InputVarType }) => void }) => (
- <div>
- <button type="button" onClick={() => onSelect({ value: InputVarType.paragraph })}>
- select-paragraph
- </button>
- <button type="button" onClick={() => onSelect({ value: InputVarType.select })}>
- select-select
- </button>
- <button type="button" onClick={() => onSelect({ value: InputVarType.singleFile })}>
- select-file
- </button>
- <button type="button" onClick={() => onSelect({ value: InputVarType.multiFiles })}>
- select-file-list
- </button>
- </div>
- ),
-}))
-
vi.mock('@/app/components/app/configuration/config-var/config-select', () => ({
__esModule: true,
default: ({ onChange }: { onChange: (options: string[]) => void }) => (
@@ -129,6 +109,36 @@ describe('InputField', () => {
expect(footer).not.toHaveClass('border-t')
})
+ it('should focus the field type from its visible label and save the selected type', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ render(
+ <InputField
+ nodeId="node-type-label"
+ isEdit
+ payload={createPayload()}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+
+ const label = screen.getByText('workflow.nodes.humanInput.insertInputField.fieldType')
+ const typeSelector = screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ })
+ await user.click(label)
+ expect(typeSelector).toHaveFocus()
+ await user.click(typeSelector)
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.select\b/ }),
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ type: InputVarType.select, output_variable_name: 'valid_name' }),
+ )
+ })
+
it('should disable save and show validation error when variable name is invalid', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
@@ -443,7 +453,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.select\b/ }),
+ )
await user.click(
screen.getByRole('button', {
name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i,
@@ -482,12 +499,26 @@ describe('InputField', () => {
screen.getByText('workflow.nodes.humanInput.insertInputField.prePopulateField'),
).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'select-file' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.single-file\b/ }),
+ )
expect(
screen.queryByText(/workflow\.nodes\.humanInput\.insertInputField\.prePopulateField/i),
).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'select-paragraph' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.paragraph\b/ }),
+ )
expect(
screen.getByText('workflow.nodes.humanInput.insertInputField.prePopulateField'),
).toBeInTheDocument()
@@ -507,7 +538,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.select\b/ }),
+ )
await user.click(screen.getByRole('button', { name: 'config-select' }))
await user.click(
screen.getByRole('button', {
@@ -541,7 +579,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.select\b/ }),
+ )
await user.click(screen.getByRole('button', { name: 'config-select' }))
await user.click(
screen.getByText(/workflow\.nodes\.humanInput\.insertInputField\.useVarInstead/i),
@@ -581,7 +626,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.select\b/ }),
+ )
await user.click(
screen.getByText(/workflow\.nodes\.humanInput\.insertInputField\.useVarInstead/i),
)
@@ -611,7 +663,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-select' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.select\b/ }),
+ )
await user.click(
screen.getByRole('button', {
name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i,
@@ -636,7 +695,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-file' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.single-file\b/ }),
+ )
await user.click(screen.getByRole('button', { name: 'file-upload-setting' }))
await user.click(
screen.getByRole('button', {
@@ -674,7 +740,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-file' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.single-file\b/ }),
+ )
await user.click(
screen.getByRole('button', {
name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i,
@@ -699,7 +772,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-file-list' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.multi-files\b/ }),
+ )
await user.click(screen.getByRole('button', { name: 'file-upload-setting' }))
await user.click(
screen.getByRole('button', {
@@ -733,7 +813,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-file-list' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.multi-files\b/ }),
+ )
await user.click(screen.getByRole('button', { name: 'file-upload-setting' }))
await user.click(
screen.getByRole('button', {
@@ -770,7 +857,14 @@ describe('InputField', () => {
/>,
)
- await user.click(screen.getByRole('button', { name: 'select-file-list' }))
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflow.nodes.humanInput.insertInputField.fieldType',
+ }),
+ )
+ await user.click(
+ await screen.findByRole('option', { name: /appDebug\.variableConfig\.multi-files\b/ }),
+ )
await user.click(
screen.getByRole('button', {
name: /workflow\.nodes\.humanInput\.insertInputField\.insert/i,
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
index f3e51fce7d7..71eec20702a 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
@@ -224,16 +224,13 @@ const InputField: React.FC<InputFieldProps> = ({
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-3 pt-0 pb-0">
<div className="mt-3">
- <div className="system-xs-medium text-text-secondary">
- {t(($) => $[`${i18nPrefix}.fieldType`], { ns: 'workflow' })}
- </div>
- <div className="mt-1.5">
- <TypeSelector
- value={tempPayload.type}
- items={fieldTypeItems}
- onSelect={handleTypeChange}
- />
- </div>
+ <TypeSelector
+ label={t(($) => $[`${i18nPrefix}.fieldType`], { ns: 'workflow' })}
+ labelClassName="mb-1.5 system-xs-medium"
+ value={tempPayload.type}
+ items={fieldTypeItems}
+ onSelect={handleTypeChange}
+ />
</div>
<div className="mt-3">
<label
diff --git a/web/app/components/base/tag-input/index.tsx b/web/app/components/base/tag-input/index.tsx
index 1bbe631000e..f40b8e7c418 100644
--- a/web/app/components/base/tag-input/index.tsx
+++ b/web/app/components/base/tag-input/index.tsx
@@ -1,10 +1,13 @@
-import type { ChangeEvent, KeyboardEvent } from 'react'
+import type { ChangeEvent, InputHTMLAttributes, KeyboardEvent } from 'react'
import { cn } from '@langgenius/dify-ui/cn'
import { toast } from '@langgenius/dify-ui/toast'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-type TagInputProps = {
+type TagInputProps = Pick<
+ InputHTMLAttributes<HTMLInputElement>,
+ 'aria-label' | 'aria-describedby' | 'aria-invalid'
+> & {
items: string[]
onChange: (items: string[]) => void
disableRemove?: boolean
@@ -26,6 +29,9 @@ const TagInput = ({
placeholder,
required = false,
inputClassName,
+ 'aria-label': ariaLabel,
+ 'aria-describedby': ariaDescribedBy,
+ 'aria-invalid': ariaInvalid,
}: TagInputProps) => {
const { t } = useTranslation()
const [value, setValue] = useState('')
@@ -66,7 +72,7 @@ const TagInput = ({
const handleKeyDown = (e: KeyboardEvent) => {
if (isSpecialMode && e.key === 'Enter') setValue(`${value}↵`)
if (e.key === customizedConfirmKey) {
- if (isSpecialMode) e.preventDefault()
+ e.preventDefault()
handleNewTag(value)
}
}
@@ -126,6 +132,9 @@ const TagInput = ({
)}
>
<input
+ aria-label={ariaLabel}
+ aria-describedby={ariaDescribedBy}
+ aria-invalid={ariaInvalid}
className={cn(
'col-start-1 row-start-1 w-full min-w-0 appearance-none text-text-primary caret-[#295EFF] outline-hidden placeholder:text-text-placeholder group-hover/tag-add:placeholder:text-text-secondary',
isSpecialMode ? 'bg-transparent' : '',
diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx
index 901c2ba5ed9..6e846c65dd4 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx
@@ -1,6 +1,7 @@
import type { ModelParameterRule } from '../../declarations'
import type { Node, NodeOutPutVar } from '@/app/components/workflow/types'
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { BlockEnum } from '@/app/components/workflow/types'
import ParameterItem from '../parameter-item'
@@ -199,10 +200,11 @@ describe('ParameterItem', () => {
expect(onChange).toHaveBeenCalledWith(false)
})
- it('should call onSwitch with current value when optional switch is toggled off', () => {
+ it('should name the optional switch after its parameter and toggle it off', async () => {
+ const user = userEvent.setup()
const onSwitch = vi.fn()
render(<ParameterItem parameterRule={createRule()} value={0.7} onSwitch={onSwitch} />)
- fireEvent.click(screen.getByRole('switch'))
+ await user.click(screen.getByRole('switch', { name: 'Temperature' }))
expect(onSwitch).toHaveBeenCalledWith(false, 0.7)
})
diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.tsx
index 5d2b31d02f1..1e0149ea5fd 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.tsx
@@ -23,7 +23,7 @@ import {
SliderTrack,
} from '@langgenius/dify-ui/slider'
import { Switch } from '@langgenius/dify-ui/switch'
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useEffect, useId, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Infotip } from '@/app/components/base/infotip'
import PromptEditor from '@/app/components/base/prompt-editor'
@@ -55,6 +55,7 @@ function ParameterItem({
}: ParameterItemProps) {
const { t } = useTranslation()
const language = useLanguage()
+ const labelId = useId()
const [localValue, setLocalValue] = useState(value)
const numberInputRef = useRef<HTMLInputElement>(null)
@@ -429,6 +430,7 @@ function ParameterItem({
{!parameterRule.required && parameterRule.name !== 'stop' && (
<div className="mr-2 w-7">
<Switch
+ aria-labelledby={labelId}
checked={!isNullOrUndefined(value)}
onCheckedChange={handleSwitch}
size="md"
@@ -436,6 +438,7 @@ function ParameterItem({
</div>
)}
<div
+ id={labelId}
className="mr-0.5 truncate system-xs-regular text-text-secondary"
title={sliderLabel}
>
diff --git a/web/app/components/plugins/plugin-auth/authorized/item.tsx b/web/app/components/plugins/plugin-auth/authorized/item.tsx
index 7bef9a46149..52e67434522 100644
--- a/web/app/components/plugins/plugin-auth/authorized/item.tsx
+++ b/web/app/components/plugins/plugin-auth/authorized/item.tsx
@@ -156,7 +156,7 @@ const Item = ({
<Badge className="shrink-0">{t(($) => $['auth.enterprise'], { ns: 'plugin' })}</Badge>
)}
{showAction && !renaming && (
- <div className="ml-2 hidden shrink-0 items-center group-hover:flex">
+ <div className="ml-2 flex shrink-0 items-center">
{!credential.is_default &&
!disableSetDefault &&
!credential.not_allowed_to_use &&
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/file-support.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/file-support.spec.tsx
index 37a8b128a40..697416791ae 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/file-support.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/file-support.spec.tsx
@@ -91,6 +91,181 @@ describe('File upload support components', () => {
})
describe('FileUploadSetting', () => {
+ it.each([false, true])(
+ 'should associate file type errors with the checkboxes in feature panel mode %s',
+ async (inFeaturePanel) => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const payload = createPayload({ allowed_file_types: [] })
+ const { rerender } = render(
+ <FileUploadSetting
+ payload={payload}
+ isMultiple={false}
+ inFeaturePanel={inFeaturePanel}
+ validationError={{ field: 'allowed_file_types', message: 'Choose a file type' }}
+ onChange={onChange}
+ />,
+ )
+
+ for (const checkbox of screen.getAllByRole('checkbox')) {
+ expect(checkbox).toBeInvalid()
+ expect(checkbox).toHaveAccessibleDescription('Choose a file type')
+ }
+ await user.click(
+ screen.getByRole('checkbox', { name: 'appDebug.variableConfig.file.document.name' }),
+ )
+ expect(onChange).toHaveBeenLastCalledWith({
+ ...payload,
+ allowed_file_types: [SupportUploadFileTypes.document],
+ })
+
+ rerender(
+ <FileUploadSetting
+ payload={createPayload()}
+ isMultiple={false}
+ inFeaturePanel={inFeaturePanel}
+ onChange={onChange}
+ />,
+ )
+ expect(screen.queryByText('Choose a file type')).not.toBeInTheDocument()
+ for (const checkbox of screen.getAllByRole('checkbox')) {
+ expect(checkbox).not.toBeInvalid()
+ expect(checkbox).not.toHaveAccessibleDescription()
+ }
+ },
+ )
+
+ it.each([false, true])(
+ 'should associate extension errors only with the named tag input in feature panel mode %s',
+ async (inFeaturePanel) => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const payload = createPayload({
+ allowed_file_types: [SupportUploadFileTypes.custom],
+ allowed_file_extensions: [],
+ })
+ const { rerender } = render(
+ <FileUploadSetting
+ payload={payload}
+ isMultiple={false}
+ inFeaturePanel={inFeaturePanel}
+ validationError={{ field: 'allowed_file_extensions', message: 'Add an extension' }}
+ onChange={onChange}
+ />,
+ )
+
+ const input = screen.getByRole('textbox', {
+ name: 'appDebug.variableConfig.file.custom.name',
+ })
+ expect(input).toBeInvalid()
+ expect(input).toHaveAccessibleDescription('Add an extension')
+ expect(
+ screen.getByRole('checkbox', { name: 'appDebug.variableConfig.file.custom.name' }),
+ ).not.toBeInvalid()
+ await user.type(input, '.csv{Enter}')
+ expect(onChange).toHaveBeenLastCalledWith({
+ ...payload,
+ allowed_file_extensions: ['.csv'],
+ })
+
+ rerender(
+ <FileUploadSetting
+ payload={{ ...payload, allowed_file_extensions: ['.csv'] }}
+ isMultiple={false}
+ inFeaturePanel={inFeaturePanel}
+ onChange={onChange}
+ />,
+ )
+ expect(input).not.toBeInvalid()
+ expect(input).not.toHaveAccessibleDescription()
+ expect(screen.queryByText('Add an extension')).not.toBeInTheDocument()
+ },
+ )
+
+ it('should let keyboard users change upload methods while preserving the rest of the settings', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const initialPayload = createPayload()
+ const StatefulFileUploadSetting = () => {
+ const [payload, setPayload] = useState(initialPayload)
+
+ return (
+ <>
+ <FileUploadSetting
+ payload={payload}
+ isMultiple={false}
+ inFeaturePanel
+ hideSupportFileType
+ onChange={(nextPayload) => {
+ setPayload(nextPayload)
+ onChange(nextPayload)
+ }}
+ />
+ <button type="button">Done</button>
+ </>
+ )
+ }
+
+ render(<StatefulFileUploadSetting />)
+
+ expect(
+ screen.getByRole('radiogroup', { name: 'appDebug.variableConfig.uploadFileTypes' }),
+ ).toBeInTheDocument()
+ await user.tab()
+ expect(
+ screen.getByRole('radio', { name: 'appDebug.variableConfig.localUpload' }),
+ ).toHaveFocus()
+ await user.keyboard('{ArrowRight}')
+ expect(screen.getByRole('radio', { name: 'URL' })).toBeChecked()
+ expect(onChange).toHaveBeenLastCalledWith({
+ ...initialPayload,
+ allowed_file_upload_methods: [TransferMethod.remote_url],
+ })
+
+ await user.keyboard('{ArrowRight}')
+ expect(screen.getByRole('radio', { name: 'appDebug.variableConfig.both' })).toBeChecked()
+ expect(onChange).toHaveBeenLastCalledWith({
+ ...initialPayload,
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ })
+
+ await user.keyboard('{ArrowRight}')
+ expect(
+ screen.getByRole('radio', { name: 'appDebug.variableConfig.localUpload' }),
+ ).toBeChecked()
+ expect(onChange).toHaveBeenLastCalledWith(initialPayload)
+ await user.tab()
+ expect(screen.getByRole('button', { name: 'Done' })).toHaveFocus()
+ })
+
+ it('should keep empty and updated upload method selections controlled by the payload', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const payload = createPayload({ allowed_file_upload_methods: [] })
+ const { rerender } = render(
+ <FileUploadSetting payload={payload} isMultiple={false} onChange={onChange} />,
+ )
+
+ expect(screen.queryByRole('radio', { checked: true })).not.toBeInTheDocument()
+ await user.click(screen.getByText('URL'))
+ expect(onChange).toHaveBeenLastCalledWith({
+ ...payload,
+ allowed_file_upload_methods: [TransferMethod.remote_url],
+ })
+
+ rerender(
+ <FileUploadSetting
+ payload={{ ...payload, allowed_file_upload_methods: [TransferMethod.remote_url] }}
+ isMultiple={false}
+ onChange={onChange}
+ />,
+ )
+ expect(screen.getByRole('radio', { name: 'URL' })).toBeChecked()
+
+ rerender(<FileUploadSetting payload={payload} isMultiple={false} onChange={onChange} />)
+ expect(screen.queryByRole('radio', { checked: true })).not.toBeInTheDocument()
+ })
+
it('should update file types, upload methods, and upload limits', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
@@ -121,7 +296,7 @@ describe('File upload support components', () => {
it('should keep upload limits within the configured range', () => {
const StatefulFileUploadSetting = () => {
- const [payload, setPayload] = useState(createPayload())
+ const [payload, setPayload] = useState(createPayload)
return <FileUploadSetting payload={payload} isMultiple onChange={setPayload} />
}
diff --git a/web/app/components/workflow/nodes/_base/components/file-type-item.tsx b/web/app/components/workflow/nodes/_base/components/file-type-item.tsx
index b691698042a..2d707b0850f 100644
--- a/web/app/components/workflow/nodes/_base/components/file-type-item.tsx
+++ b/web/app/components/workflow/nodes/_base/components/file-type-item.tsx
@@ -22,6 +22,8 @@ type Props = Readonly<{
onToggle: (type: SupportUploadFileTypes) => void
onCustomFileTypesChange?: (customFileTypes: string[]) => void
customFileTypes?: string[]
+ typeErrorId?: string
+ customFileTypesErrorId?: string
}>
const FileTypeItem: FC<Props> = ({
@@ -30,6 +32,8 @@ const FileTypeItem: FC<Props> = ({
onToggle,
customFileTypes = [],
onCustomFileTypesChange = noop,
+ typeErrorId,
+ customFileTypesErrorId,
}) => {
const { t } = useTranslation()
@@ -62,10 +66,15 @@ const FileTypeItem: FC<Props> = ({
className="shrink-0"
checked={selected}
aria-label={t(($) => $[`variableConfig.file.${type}.name`], { ns: 'appDebug' })}
+ aria-invalid={typeErrorId ? true : undefined}
+ aria-describedby={typeErrorId}
/>
</div>
<div className="p-3" onClick={(e) => e.stopPropagation()}>
<TagInput
+ aria-label={t(($) => $['variableConfig.file.custom.name'], { ns: 'appDebug' })}
+ aria-invalid={customFileTypesErrorId ? true : undefined}
+ aria-describedby={customFileTypesErrorId}
items={customFileTypes}
onChange={onCustomFileTypesChange}
placeholder={t(($) => $['variableConfig.file.custom.createPlaceholder'], {
@@ -91,6 +100,8 @@ const FileTypeItem: FC<Props> = ({
className="shrink-0"
checked={selected}
aria-label={t(($) => $[`variableConfig.file.${type}.name`], { ns: 'appDebug' })}
+ aria-invalid={typeErrorId ? true : undefined}
+ aria-describedby={typeErrorId}
/>
</div>
)}
diff --git a/web/app/components/workflow/nodes/_base/components/file-upload-setting.tsx b/web/app/components/workflow/nodes/_base/components/file-upload-setting.tsx
index 3aafd8f2a0c..558cfba4db5 100644
--- a/web/app/components/workflow/nodes/_base/components/file-upload-setting.tsx
+++ b/web/app/components/workflow/nodes/_base/components/file-upload-setting.tsx
@@ -1,9 +1,13 @@
'use client'
import type { FC } from 'react'
import type { UploadFileSetting } from '../../../types'
+import { cn } from '@langgenius/dify-ui/cn'
+import { FieldItem, FieldLabel, Field as FormField } from '@langgenius/dify-ui/field'
+import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
+import { RadioGroup, RadioItem } from '@langgenius/dify-ui/radio-group'
import { produce } from 'immer'
import * as React from 'react'
-import { useCallback } from 'react'
+import { useCallback, useId } from 'react'
import { useTranslation } from 'react-i18next'
import Field from '@/app/components/app/configuration/config-var/config-modal/field'
import { useFileSizeLimit } from '@/app/components/base/file-uploader/hooks'
@@ -13,13 +17,16 @@ import { formatFileSize } from '@/utils/format'
import { SupportUploadFileTypes } from '../../../types'
import FileTypeItem from './file-type-item'
import InputNumberWithSlider from './input-number-with-slider'
-import OptionCard from './option-card'
type Props = Readonly<{
payload: UploadFileSetting
isMultiple: boolean
inFeaturePanel?: boolean
hideSupportFileType?: boolean
+ validationError?: {
+ field: 'allowed_file_types' | 'allowed_file_extensions'
+ message: string
+ }
onChange: (payload: UploadFileSetting) => void
}>
@@ -28,9 +35,14 @@ const FileUploadSetting: FC<Props> = ({
isMultiple,
inFeaturePanel = false,
hideSupportFileType = false,
+ validationError,
onChange,
}) => {
const { t } = useTranslation()
+ const errorId = useId()
+ const typeErrorId = validationError?.field === 'allowed_file_types' ? errorId : undefined
+ const customFileTypesErrorId =
+ validationError?.field === 'allowed_file_extensions' ? errorId : undefined
const {
allowed_file_upload_methods = [],
@@ -64,22 +76,35 @@ const FileUploadSetting: FC<Props> = ({
)
const handleUploadMethodChange = useCallback(
- (method: TransferMethod) => {
- return () => {
- const newPayload = produce(payload, (draft) => {
- if (method === TransferMethod.all)
- draft.allowed_file_upload_methods = [
- TransferMethod.local_file,
- TransferMethod.remote_url,
- ]
- else draft.allowed_file_upload_methods = [method]
- })
- onChange(newPayload)
- }
+ (method: TransferMethod | null) => {
+ if (method === null) return
+ const newPayload = produce(payload, (draft) => {
+ draft.allowed_file_upload_methods =
+ method === TransferMethod.all
+ ? [TransferMethod.local_file, TransferMethod.remote_url]
+ : [method]
+ })
+ onChange(newPayload)
},
[onChange, payload],
)
+ const selectedMethod = allowed_file_upload_methods.includes(TransferMethod.local_file)
+ ? allowed_file_upload_methods.includes(TransferMethod.remote_url)
+ ? TransferMethod.all
+ : TransferMethod.local_file
+ : allowed_file_upload_methods.includes(TransferMethod.remote_url)
+ ? TransferMethod.remote_url
+ : null
+ const uploadMethods = [
+ {
+ value: TransferMethod.local_file,
+ label: t(($) => $['variableConfig.localUpload'], { ns: 'appDebug' }),
+ },
+ { value: TransferMethod.remote_url, label: 'URL' },
+ { value: TransferMethod.all, label: t(($) => $['variableConfig.both'], { ns: 'appDebug' }) },
+ ]
+
const handleCustomFileTypesChange = useCallback(
(customFileTypes: string[]) => {
const newPayload = produce(payload, (draft) => {
@@ -108,7 +133,11 @@ const FileUploadSetting: FC<Props> = ({
return (
<div>
{!inFeaturePanel && (
- <Field title={t(($) => $['variableConfig.file.supportFileTypes'], { ns: 'appDebug' })}>
+ <Field
+ title={t(($) => $['variableConfig.file.supportFileTypes'], { ns: 'appDebug' })}
+ errorMessage={validationError?.message}
+ errorId={errorId}
+ >
<div className="space-y-1">
{[
SupportUploadFileTypes.document,
@@ -127,6 +156,7 @@ const FileUploadSetting: FC<Props> = ({
}
selected={allowed_file_types.includes(type)}
onToggle={handleSupportFileTypeChange}
+ typeErrorId={typeErrorId}
/>
))}
<FileTypeItem
@@ -135,41 +165,45 @@ const FileUploadSetting: FC<Props> = ({
onToggle={handleSupportFileTypeChange}
customFileTypes={allowed_file_extensions}
onCustomFileTypesChange={handleCustomFileTypesChange}
+ typeErrorId={typeErrorId}
+ customFileTypesErrorId={customFileTypesErrorId}
/>
</div>
</Field>
)}
- <Field
- title={t(($) => $['variableConfig.uploadFileTypes'], { ns: 'appDebug' })}
- className="mt-4"
- >
- <div className="grid grid-cols-3 gap-2">
- <OptionCard
- title={t(($) => $['variableConfig.localUpload'], { ns: 'appDebug' })}
- selected={
- allowed_file_upload_methods.length === 1 &&
- allowed_file_upload_methods.includes(TransferMethod.local_file)
- }
- onSelect={handleUploadMethodChange(TransferMethod.local_file)}
- />
- <OptionCard
- title="URL"
- selected={
- allowed_file_upload_methods.length === 1 &&
- allowed_file_upload_methods.includes(TransferMethod.remote_url)
- }
- onSelect={handleUploadMethodChange(TransferMethod.remote_url)}
- />
- <OptionCard
- title={t(($) => $['variableConfig.both'], { ns: 'appDebug' })}
- selected={
- allowed_file_upload_methods.includes(TransferMethod.local_file) &&
- allowed_file_upload_methods.includes(TransferMethod.remote_url)
- }
- onSelect={handleUploadMethodChange(TransferMethod.all)}
- />
- </div>
- </Field>
+ <FormField className="mt-4">
+ <Fieldset
+ className="flex flex-col items-stretch gap-0"
+ render={
+ <RadioGroup<TransferMethod | null>
+ value={selectedMethod}
+ onValueChange={handleUploadMethodChange}
+ />
+ }
+ >
+ <FieldsetLegend className="mb-0 py-0 system-sm-semibold leading-8!">
+ {t(($) => $['variableConfig.uploadFileTypes'], { ns: 'appDebug' })}
+ </FieldsetLegend>
+ <div className="grid grid-cols-3 gap-2">
+ {uploadMethods.map((method) => (
+ <FieldItem key={method.value}>
+ <FieldLabel className="block w-full min-w-0 py-0">
+ <RadioItem<TransferMethod>
+ value={method.value}
+ className={cn(
+ 'flex h-8 w-full cursor-default items-center justify-center rounded-md border border-components-option-card-option-border bg-components-option-card-option-bg px-2 system-sm-regular text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-checked:border-[1.5px] data-checked:border-components-option-card-option-selected-border data-checked:bg-components-option-card-option-selected-bg data-checked:shadow-xs',
+ selectedMethod !== method.value &&
+ 'cursor-pointer hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',
+ )}
+ >
+ <span>{method.label}</span>
+ </RadioItem>
+ </FieldLabel>
+ </FieldItem>
+ ))}
+ </div>
+ </Fieldset>
+ </FormField>
{isMultiple && (
<Field
className="mt-4"
@@ -201,6 +235,8 @@ const FileUploadSetting: FC<Props> = ({
<Field
title={t(($) => $['variableConfig.file.supportFileTypes'], { ns: 'appDebug' })}
className="mt-4"
+ errorMessage={validationError?.message}
+ errorId={errorId}
>
<div className="space-y-1">
{[
@@ -220,6 +256,7 @@ const FileUploadSetting: FC<Props> = ({
}
selected={allowed_file_types.includes(type)}
onToggle={handleSupportFileTypeChange}
+ typeErrorId={typeErrorId}
/>
))}
<FileTypeItem
@@ -228,6 +265,8 @@ const FileUploadSetting: FC<Props> = ({
onToggle={handleSupportFileTypeChange}
customFileTypes={allowed_file_extensions}
onCustomFileTypesChange={handleCustomFileTypesChange}
+ typeErrorId={typeErrorId}
+ customFileTypesErrorId={customFileTypesErrorId}
/>
</div>
</Field>
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/email-configure-modal.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/email-configure-modal.spec.tsx
index 3388236f0eb..e413ce6b83c 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/email-configure-modal.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/email-configure-modal.spec.tsx
@@ -126,7 +126,11 @@ describe('human-input/delivery-method/email-configure-modal', () => {
target: { value: 'Please review {{#url#}} now' },
})
fireEvent.click(screen.getByRole('button', { name: 'set-workspace-recipient' }))
- fireEvent.click(screen.getByRole('switch'))
+ fireEvent.click(
+ screen.getByRole('switch', {
+ name: 'workflow.nodes.humanInput.deliveryMethod.emailConfigure.debugMode',
+ }),
+ )
fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(handleConfirm).toHaveBeenCalledWith({
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/email-configure-modal.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/email-configure-modal.tsx
index 2a4f8614eec..254e726cb3f 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/email-configure-modal.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/email-configure-modal.tsx
@@ -35,6 +35,8 @@ const EmailConfigureModal = ({
}: EmailConfigureModalProps) => {
const { t } = useTranslation()
const subjectId = useId()
+ const debugModeId = useId()
+ const debugDescriptionId = useId()
const { data: email } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.profile.email,
@@ -160,12 +162,12 @@ const EmailConfigureModal = ({
<RiBugLine className="size-3.5 text-text-primary-on-surface" />
</div>
<div className="grow space-y-1">
- <div className="system-sm-medium text-text-secondary">
+ <label htmlFor={debugModeId} className="system-sm-medium text-text-secondary">
{t(($) => $[`${i18nPrefix}.deliveryMethod.emailConfigure.debugMode`], {
ns: 'workflow',
})}
- </div>
- <div className="body-xs-regular text-text-tertiary">
+ </label>
+ <div id={debugDescriptionId} className="body-xs-regular text-text-tertiary">
<Trans
i18nKey={($) => $[`${i18nPrefix}.deliveryMethod.emailConfigure.debugModeTip1`]}
ns="workflow"
@@ -181,7 +183,12 @@ const EmailConfigureModal = ({
</div>
</div>
</div>
- <Switch checked={debugMode} onCheckedChange={(checked) => setDebugMode(checked)} />
+ <Switch
+ id={debugModeId}
+ aria-describedby={debugDescriptionId}
+ checked={debugMode}
+ onCheckedChange={(checked) => setDebugMode(checked)}
+ />
</div>
</div>
<div className="mt-6 flex flex-row-reverse gap-2">
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx
index 556757693dc..e8830157674 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/email-input.spec.tsx
@@ -1,6 +1,7 @@
import type { Recipient as RecipientItem } from '../../../../types'
import type { Member } from '@/models/common'
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import EmailInput from '../email-input'
const mockEmailItem = vi.hoisted(() => vi.fn())
@@ -135,6 +136,59 @@ describe('human-input/delivery-method/recipient/email-input', () => {
expect(handleSelect).toHaveBeenCalledTimes(1)
})
+ it.each([
+ { value: '', expectedAdds: 0 },
+ { value: 'bad-email', expectedAdds: 0 },
+ { value: '[email protected]', expectedAdds: 0 },
+ { value: '[email protected]', expectedAdds: 1 },
+ ])(
+ 'should allow Tab to leave "$value" and add a valid email only once',
+ async ({ value, expectedAdds }) => {
+ const user = userEvent.setup()
+ const handleAdd = vi.fn()
+ render(
+ <>
+ <EmailInput
+ value={[{ type: 'external', email: '[email protected]' }]}
+ list={members}
+ onDelete={vi.fn()}
+ onSelect={vi.fn()}
+ onAdd={handleAdd}
+ />
+ <button type="button">Save</button>
+ </>,
+ )
+ const input = screen.getByRole('textbox')
+ await user.click(input)
+ if (value) await user.type(input, value)
+ await user.tab()
+ expect(screen.getByRole('button', { name: 'Save' })).toHaveFocus()
+ expect(handleAdd).toHaveBeenCalledTimes(expectedAdds)
+ if (expectedAdds) expect(handleAdd).toHaveBeenCalledWith(value)
+ },
+ )
+
+ it('should allow Shift+Tab to return to the previous control', async () => {
+ const user = userEvent.setup()
+ render(
+ <>
+ <button type="button">Previous</button>
+ <EmailInput
+ value={[]}
+ list={members}
+ onDelete={vi.fn()}
+ onSelect={vi.fn()}
+ onAdd={vi.fn()}
+ />
+ </>,
+ )
+ await user.click(screen.getByRole('textbox'))
+ await user.tab({ shift: true })
+ expect(screen.getByRole('button', { name: 'Previous' })).toHaveFocus()
+ })
+
it('should keep typing focused and stop keyboard events from reaching workflow listeners', () => {
const handleParentKeyDown = vi.fn()
const handleWindowKeyDown = vi.fn()
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/index.spec.tsx
index 121d353c7b6..d2a95ffd123 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/index.spec.tsx
@@ -111,7 +111,7 @@ describe('Recipient', () => {
fireEvent.click(screen.getByText('add-email-member'))
fireEvent.click(screen.getByText('delete-member'))
fireEvent.click(screen.getByText('delete-external'))
- fireEvent.click(screen.getByRole('switch'))
+ fireEvent.click(screen.getByRole('switch', { name: 'Dify’s Lab' }))
expect(onChange).toHaveBeenNthCalledWith(1, {
whole_workspace: false,
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx
index 8eaed0d8c3a..f5e72f3aa1a 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx
@@ -102,7 +102,9 @@ const EmailInput = ({ email, value, list, onDelete, onSelect, onAdd, disabled =
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
e.stopPropagation()
- if (e.key === 'Enter' || e.key === 'Tab' || e.key === ' ' || e.key === ',') {
+ if (e.key === 'Tab') {
+ setOpen(false)
+ } else if (e.key === 'Enter' || e.key === ' ' || e.key === ',') {
e.preventDefault()
handleEmailAdd()
} else if (e.key === 'Backspace') {
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/index.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/index.tsx
index 4f26c2c632f..a6f4fc1ac7a 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/index.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/index.tsx
@@ -5,7 +5,7 @@ import { RiGroupLine } from '@remixicon/react'
import { useSuspenseQuery } from '@tanstack/react-query'
import { produce } from 'immer'
import { useAtomValue } from 'jotai'
-import { memo } from 'react'
+import { memo, useId } from 'react'
import { useTranslation } from 'react-i18next'
import { currentWorkspaceAtom } from '@/context/workspace-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
@@ -22,6 +22,7 @@ type Props = Readonly<{
const Recipient = ({ data, onChange }: Props) => {
const { t } = useTranslation()
+ const wholeWorkspaceId = useId()
const { data: userProfileEmail } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.profile.email,
@@ -99,13 +100,17 @@ const Recipient = ({ data, onChange }: Props) => {
{currentWorkspace?.name[0]?.toLocaleUpperCase()}
</span>
</div>
- <div className={cn('grow system-sm-medium text-text-secondary')}>
+ <label
+ htmlFor={wholeWorkspaceId}
+ className={cn('grow system-sm-medium text-text-secondary')}
+ >
{t(($) => $[`${i18nPrefix}.deliveryMethod.emailConfigure.allMembers`], {
workspaceName: currentWorkspace.name.replace(/'/g, '’'),
ns: 'workflow',
})}
- </div>
+ </label>
<Switch
+ id={wholeWorkspaceId}
checked={data.whole_workspace}
onCheckedChange={(checked) => onChange({ ...data, whole_workspace: checked })}
/>