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.

refactor(web): move per-field errors onto Field and FieldError (#45264)

yyha79e2116f85b
diff --git a/packages/dify-ui/docs/forms.md b/packages/dify-ui/docs/forms.md
index 989160fa8ab..53e3ebc66a4 100644
--- a/packages/dify-ui/docs/forms.md
+++ b/packages/dify-ui/docs/forms.md
@@ -46,6 +46,11 @@ standalone `Input` may use a native `<label htmlFor>` relationship, but normal f
prefer a visible label. `FieldDescription` and `FieldError` provide the corresponding accessible
message relationships.
+`FieldError` follows native constraints, `validate`, and `Form` `errors`. When application code
+owns the validity instead, set `invalid` on `Field` and `match` on `FieldError`. A `Field` describes
+one control; a composite that renders its own controls, such as a picker with controls in its popup,
+does not go inside one.
+
Choose the label primitive by the control:
- Text-like inputs, `Textarea`, input-based `Combobox` and `Autocomplete`, a single `Checkbox`,
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 00c30947ea0..a23cc8d2264 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
@@ -6,6 +6,7 @@ import type { ConfigModalValidationError } from './utils'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { InputVar, UploadFileSetting } from '@/app/components/workflow/types'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
+import { Field, FieldError } from '@langgenius/dify-ui/field'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Input } from '@langgenius/dify-ui/input'
import { NumberField, NumberFieldGroup, NumberFieldInput } from '@langgenius/dify-ui/number-field'
@@ -35,7 +36,7 @@ import { TransferMethod } from '@/types/app'
import ConfigSelect from '../config-select'
import ConfigString from '../config-string'
import { jsonConfigPlaceHolder } from './config'
-import Field from './field'
+import ConfigField from './field'
import TypeSelector from './type-select'
import { CHECKBOX_DEFAULT_FALSE_VALUE, CHECKBOX_DEFAULT_TRUE_VALUE, TEXT_MAX_LENGTH } from './utils'
@@ -112,40 +113,40 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
/>
</div>
- <Field
- htmlFor={`${fieldId}-variable`}
- title={t(($) => $['variableConfig.varName'], { ns: 'appDebug' })}
- errorMessage={getError('variable')}
- errorId={errorId}
- >
+ <Field name="variable" invalid={!!getError('variable')}>
+ <label
+ htmlFor={`${fieldId}-variable`}
+ className="block system-sm-semibold leading-8! text-text-secondary"
+ >
+ {t(($) => $['variableConfig.varName'], { ns: 'appDebug' })}
+ </label>
<Input
id={`${fieldId}-variable`}
- name="variable"
- {...getErrorProps('variable')}
value={variable}
onChange={onVarNameChange}
onBlur={onVarKeyBlur}
placeholder={t(($) => $['variableConfig.inputPlaceholder'], { ns: 'appDebug' })}
/>
+ <FieldError match={!!getError('variable')}>{getError('variable')}</FieldError>
</Field>
- <Field
- htmlFor={`${fieldId}-label`}
- title={t(($) => $['variableConfig.labelName'], { ns: 'appDebug' })}
- errorMessage={getError('label')}
- errorId={errorId}
- >
+ <Field name="label" invalid={!!getError('label')}>
+ <label
+ htmlFor={`${fieldId}-label`}
+ className="block system-sm-semibold leading-8! text-text-secondary"
+ >
+ {t(($) => $['variableConfig.labelName'], { ns: 'appDebug' })}
+ </label>
<Input
id={`${fieldId}-label`}
- name="label"
- {...getErrorProps('label')}
value={label as string}
onValueChange={(value) => onPayloadChange('label')(value)}
placeholder={t(($) => $['variableConfig.inputPlaceholder'], { ns: 'appDebug' })}
/>
+ <FieldError match={!!getError('label')}>{getError('label')}</FieldError>
</Field>
{isStringInput && (
- <Field
+ <ConfigField
htmlFor={`${fieldId}-max-length`}
title={t(($) => $['variableConfig.maxLength'], { ns: 'appDebug' })}
>
@@ -156,11 +157,11 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
value={maxLength}
onChange={onPayloadChange('max_length')}
/>
- </Field>
+ </ConfigField>
)}
{type === InputVarType.textInput && (
- <Field
+ <ConfigField
htmlFor={`${fieldId}-default`}
title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}
>
@@ -171,11 +172,11 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
onValueChange={(value) => onPayloadChange('default')(value || undefined)}
placeholder={t(($) => $['variableConfig.inputPlaceholder'], { ns: 'appDebug' })}
/>
- </Field>
+ </ConfigField>
)}
{type === InputVarType.paragraph && (
- <Field
+ <ConfigField
htmlFor={`${fieldId}-default`}
title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}
>
@@ -185,11 +186,11 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
onValueChange={(value) => onPayloadChange('default')(value || undefined)}
placeholder={t(($) => $['variableConfig.inputPlaceholder'], { ns: 'appDebug' })}
/>
- </Field>
+ </ConfigField>
)}
{type === InputVarType.number && (
- <Field
+ <ConfigField
htmlFor={`${fieldId}-default`}
title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}
>
@@ -207,7 +208,7 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
/>
</NumberFieldGroup>
</NumberField>
- </Field>
+ </ConfigField>
)}
{type === InputVarType.checkbox && (
@@ -252,7 +253,7 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
{type === InputVarType.select && (
<>
- <Field
+ <ConfigField
title={t(($) => $['variableConfig.options'], { ns: 'appDebug' })}
errorMessage={getError('options')}
errorId={errorId}
@@ -263,7 +264,7 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
errorMessage={getError('options')}
errorId={errorId}
/>
- </Field>
+ </ConfigField>
{options && options.length > 0 && (
<div>
<Select<string>
@@ -328,7 +329,7 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
: undefined
}
/>
- <Field title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}>
+ <ConfigField title={t(($) => $['variableConfig.defaultValue'], { ns: 'appDebug' })}>
<FileUploaderInAttachmentWrapper
value={
(type === InputVarType.singleFile
@@ -353,12 +354,12 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
number_limits: type === InputVarType.singleFile ? 1 : tempPayload.max_length || 5,
}}
/>
- </Field>
+ </ConfigField>
</>
)}
{type === InputVarType.jsonObject && (
- <Field
+ <ConfigField
title={t(($) => $['variableConfig.jsonSchema'], { ns: 'appDebug' })}
titleId={`${fieldId}-json-schema`}
isOptional
@@ -381,7 +382,7 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
placeholder={<div className="whitespace-pre">{jsonConfigPlaceHolder}</div>}
/>
</div>
- </Field>
+ </ConfigField>
)}
<label className="mt-5! flex h-6 cursor-pointer items-center space-x-2 has-data-disabled:cursor-not-allowed">
diff --git a/web/app/components/app/deploy/__tests__/index.spec.tsx b/web/app/components/app/deploy/__tests__/index.spec.tsx
index 41ad0497a2f..2fa9f5e170f 100644
--- a/web/app/components/app/deploy/__tests__/index.spec.tsx
+++ b/web/app/components/app/deploy/__tests__/index.spec.tsx
@@ -1501,9 +1501,6 @@ describe('AppDeploy', () => {
'Server port workflow.env.modal.valueRequired',
)
expect(customPortInput).toHaveFocus()
- expect(
- within(rootVariables.getByRole('group', { name: 'PORT' })).getByRole('alert'),
- ).toHaveTextContent('workflow.env.modal.valueRequired')
await user.type(customPortInput, '3000')
expect(customPortInput).not.toHaveAttribute('aria-invalid', 'true')
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/__tests__/credential-field.spec.tsx b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/credential-field.spec.tsx
index 79aab3b1931..f8e2c563b05 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/__tests__/credential-field.spec.tsx
+++ b/web/app/components/app/deploy/shared/deployment-configuration/__tests__/credential-field.spec.tsx
@@ -59,7 +59,7 @@ function workflowPath(...workflows: WorkflowReference[]): WorkflowPath {
function renderCredentialField() {
return renderWithConsoleQuery(
- <CredentialField slot={credentialSlot} value="credential-1" onChange={vi.fn()} />,
+ <CredentialField slot={credentialSlot} defaultValue="credential-1" onChange={vi.fn()} />,
)
}
@@ -99,7 +99,7 @@ describe('CredentialField', () => {
renderWithConsoleQuery(
<CredentialField
slot={{ ...credentialSlot, candidates: [] }}
- value={undefined}
+ defaultValue={undefined}
onChange={vi.fn()}
/>,
)
@@ -125,7 +125,7 @@ describe('CredentialField', () => {
<CredentialField
slot={credentialSlot}
paths={[workflowPath(root, source)]}
- value="credential-1"
+ defaultValue="credential-1"
onChange={vi.fn()}
/>,
)
@@ -156,7 +156,7 @@ describe('CredentialField', () => {
workflowReference('Audit workflow', 'audit'),
),
]}
- value="credential-1"
+ defaultValue="credential-1"
onChange={vi.fn()}
/>,
)
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/content.tsx b/web/app/components/app/deploy/shared/deployment-configuration/content.tsx
index 8fe2b8eaefc..ee61063a715 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/content.tsx
+++ b/web/app/components/app/deploy/shared/deployment-configuration/content.tsx
@@ -4,7 +4,6 @@ import type { DeploymentDialogRequest } from '../../types'
import type { DeploymentVersion } from '../../utils/version'
import type { DeploymentConfigurationQueryState } from './use-deployment-configuration-queries'
import type { DeploymentConfigurationValuesController } from './use-deployment-configuration-values'
-import type { DeploymentFieldError } from './utils/field-id'
import { cn } from '@langgenius/dify-ui/cn'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
@@ -36,7 +35,6 @@ function ConfigurationError({ messages }: { messages: string[] }) {
export function DeploymentConfigurationContent({
compact = false,
configurationValues,
- fieldError,
onConfigurationChange,
queryState,
request,
@@ -44,7 +42,6 @@ export function DeploymentConfigurationContent({
}: {
compact?: boolean
configurationValues: DeploymentConfigurationValuesController
- fieldError?: DeploymentFieldError
onConfigurationChange: () => void
queryState: DeploymentConfigurationQueryState
request: DeploymentDialogRequest
@@ -63,7 +60,7 @@ export function DeploymentConfigurationContent({
precheckError,
} = queryState
const {
- credentials,
+ getCredential,
getEnvironmentVariableSelection,
setCredential,
setEnvironmentVariableSelection,
@@ -134,8 +131,7 @@ export function DeploymentConfigurationContent({
<>
<CredentialsSection
credentialSlots={deploymentOptions?.credential_slots ?? []}
- credentials={credentials}
- fieldError={fieldError}
+ getCredential={getCredential}
horizontalPaddingClassName={horizontalPaddingClassName}
onChange={(key, value) => {
setCredential(key, value)
@@ -144,7 +140,6 @@ export function DeploymentConfigurationContent({
/>
<EnvironmentVariablesSection
environmentVariableGroups={deploymentOptions?.environment_variable_groups ?? []}
- fieldError={fieldError}
getEnvironmentVariableSelection={getEnvironmentVariableSelection}
hasCredentialSlots={hasCredentialSlots}
horizontalPaddingClassName={horizontalPaddingClassName}
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/credential-field.tsx b/web/app/components/app/deploy/shared/deployment-configuration/credential-field.tsx
index bbfa0cc940a..49c7e3bf316 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/credential-field.tsx
+++ b/web/app/components/app/deploy/shared/deployment-configuration/credential-field.tsx
@@ -1,5 +1,6 @@
import type { CredentialSlot, WorkflowPath } from '@dify/contracts/enterprise-app-deploy/types.gen'
import { PluginCategory } from '@dify/contracts/enterprise-app-deploy/types.gen'
+import { Field, FieldError } from '@langgenius/dify-ui/field'
import {
Select,
SelectContent,
@@ -9,6 +10,7 @@ import {
SelectItemText,
SelectLabel,
SelectTrigger,
+ SelectValue,
} from '@langgenius/dify-ui/select'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { useTranslation } from 'react-i18next'
@@ -20,25 +22,21 @@ import { credentialProviderName } from './utils/workflow-deployment-input'
import { WorkflowDependencyPreview } from './workflow-source-popover'
export function CredentialField({
- error,
slot,
paths = [],
- value,
+ defaultValue,
onChange,
}: {
- error?: string
slot: CredentialSlot
paths?: WorkflowPath[]
- value?: string
+ defaultValue?: string
onChange: (value: string) => void
}) {
const { t } = useTranslation(['deployments'])
const { t: tPlugin } = useTranslation(['plugin'])
const { getIconUrl } = useGetIcon()
const { theme } = useTheme()
- const selectedOption = slot.candidates.find((candidate) => candidate.credential_id === value)
const inputId = credentialFieldId(slot)
- const errorId = `${inputId}-error`
const name = credentialProviderName(slot.provider_id)
const iconFileName =
theme === Theme.dark ? slot.icon_dark || slot.icon : slot.icon || slot.icon_dark
@@ -51,13 +49,13 @@ export function CredentialField({
: ''
return (
- <Select
- value={value ?? null}
- onValueChange={(nextValue) => {
- if (nextValue) onChange(nextValue)
- }}
- >
- <div className="flex min-w-0 flex-col gap-1">
+ <Field name={inputId}>
+ <Select
+ defaultValue={defaultValue ?? null}
+ onValueChange={(nextValue) => {
+ if (nextValue) onChange(nextValue)
+ }}
+ >
<div className="flex min-w-0 items-center justify-between gap-2 py-0.5">
<div className="flex min-w-0 flex-1 items-center gap-1">
<span className="size-5 shrink-0 overflow-hidden rounded-md border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge">
@@ -79,20 +77,18 @@ export function CredentialField({
</div>
<WorkflowDependencyPreview subjectName={name} paths={paths} />
</div>
- <SelectTrigger
- id={inputId}
- aria-invalid={Boolean(error)}
- aria-describedby={error ? errorId : undefined}
- className="ps-2"
- >
+ <SelectTrigger id={inputId} className="ps-2">
<span className="flex min-w-0 items-center gap-1.5">
<StatusDot />
- <span className="truncate text-text-secondary">
- {selectedOption?.display_name ??
+ <SelectValue<string> className="truncate text-text-secondary">
+ {(value) =>
+ slot.candidates.find((candidate) => candidate.credential_id === value)
+ ?.display_name ??
(slot.candidates.length === 0
? t(($) => $['deployDrawer.noCredentialCandidates'])
- : t(($) => $['deployDrawer.selectCredential']))}
- </span>
+ : t(($) => $['deployDrawer.selectCredential']))
+ }
+ </SelectValue>
</span>
</SelectTrigger>
<SelectContent className="w-(--anchor-width) bg-components-panel-bg-blur backdrop-blur-[5px]">
@@ -130,12 +126,8 @@ export function CredentialField({
</SelectGroup>
)}
</SelectContent>
- {error && (
- <p id={errorId} role="alert" className="system-xs-regular text-text-destructive">
- {error}
- </p>
- )}
- </div>
- </Select>
+ </Select>
+ <FieldError />
+ </Field>
)
}
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/credentials-section.tsx b/web/app/components/app/deploy/shared/deployment-configuration/credentials-section.tsx
index 82f13eff786..c858b1707b9 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/credentials-section.tsx
+++ b/web/app/components/app/deploy/shared/deployment-configuration/credentials-section.tsx
@@ -1,36 +1,31 @@
import type { CredentialSlot } from '@dify/contracts/enterprise-app-deploy/types.gen'
import type { DeploymentConfigurationValuesController } from './use-deployment-configuration-values'
-import type { DeploymentFieldError } from './utils/field-id'
import { cn } from '@langgenius/dify-ui/cn'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import { CredentialField } from './credential-field'
import { SectionHeading } from './section-heading'
-import { credentialFieldId } from './utils/field-id'
import { credentialSlotKey, defaultCredentialId } from './utils/workflow-deployment-input'
const CredentialConfigurationField = memo(
({
- error,
onChange,
paths,
slot,
slotKey,
- value,
+ defaultValue,
}: {
- error?: string
onChange: DeploymentConfigurationValuesController['setCredential']
paths?: NonNullable<CredentialSlot['workflow_as_tool_dependency']>['paths']
slot: CredentialSlot
slotKey: string
- value?: string
+ defaultValue?: string
}) => {
return (
<CredentialField
- error={error}
paths={paths}
slot={slot}
- value={value}
+ defaultValue={defaultValue}
onChange={(value) => onChange(slotKey, value)}
/>
)
@@ -41,14 +36,12 @@ CredentialConfigurationField.displayName = 'CredentialConfigurationField'
export const CredentialsSection = memo(
({
credentialSlots,
- credentials,
- fieldError,
+ getCredential,
horizontalPaddingClassName,
onChange,
}: {
credentialSlots: CredentialSlot[]
- credentials: DeploymentConfigurationValuesController['credentials']
- fieldError?: DeploymentFieldError
+ getCredential: DeploymentConfigurationValuesController['getCredential']
horizontalPaddingClassName: string
onChange: DeploymentConfigurationValuesController['setCredential']
}) => {
@@ -72,13 +65,10 @@ export const CredentialsSection = memo(
return (
<CredentialConfigurationField
- error={
- fieldError?.fieldId === credentialFieldId(slot) ? fieldError.message : undefined
- }
key={slotKey}
slot={slot}
slotKey={slotKey}
- value={credentials[slotKey] ?? defaultCredentialId(slot)}
+ defaultValue={getCredential(slotKey) ?? defaultCredentialId(slot)}
onChange={onChange}
/>
)
@@ -100,14 +90,11 @@ export const CredentialsSection = memo(
return (
<CredentialConfigurationField
- error={
- fieldError?.fieldId === credentialFieldId(slot) ? fieldError.message : undefined
- }
key={slotKey}
paths={slot.workflow_as_tool_dependency?.paths}
slot={slot}
slotKey={slotKey}
- value={credentials[slotKey] ?? defaultCredentialId(slot)}
+ defaultValue={getCredential(slotKey) ?? defaultCredentialId(slot)}
onChange={onChange}
/>
)
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/environment-variable-field.tsx b/web/app/components/app/deploy/shared/deployment-configuration/environment-variable-field.tsx
index 8606a55df7d..26179e09b43 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/environment-variable-field.tsx
+++ b/web/app/components/app/deploy/shared/deployment-configuration/environment-variable-field.tsx
@@ -10,6 +10,7 @@ import {
EnvVarValueSource as EnvVarValueSourceEnum,
EnvVarValueType,
} from '@dify/contracts/enterprise-app-deploy/types.gen'
+import { Field, FieldDescription, FieldError } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
import {
Select,
@@ -51,13 +52,11 @@ function displayEnvironmentVariableValue(value: unknown) {
export const EnvironmentVariableField = memo(
({
- error,
slot,
workflowId,
getInitialSelection,
onChange,
}: {
- error?: string
slot: EnvironmentVariableSlot
workflowId: string
getInitialSelection: (
@@ -100,8 +99,6 @@ export const EnvironmentVariableField = memo(
const labelId = `${inputId}-label`
const descriptionId = `${inputId}-description`
const errorId = `${inputId}-error`
- const describedBy =
- [slot.description && descriptionId, error && errorId].filter(Boolean).join(' ') || undefined
const editable = source === EnvVarValueSourceEnum.ENV_VAR_VALUE_SOURCE_CUSTOM
const inputType =
editable && slot.value_type === EnvVarValueType.ENV_VAR_VALUE_TYPE_SECRET
@@ -206,7 +203,9 @@ export const EnvironmentVariableField = memo(
tabIndex={-1}
role="group"
aria-labelledby={labelId}
- aria-describedby={describedBy}
+ aria-describedby={[slot.description && descriptionId, errorId]
+ .filter(Boolean)
+ .join(' ')}
className="flex w-full min-w-0 outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"
>
<LLMEnvironmentVariableValueField
@@ -221,35 +220,30 @@ export const EnvironmentVariableField = memo(
}
/>
</div>
- ) : (
- <Input
- id={inputId}
- aria-describedby={describedBy}
- aria-invalid={Boolean(error)}
- step={inputType === 'number' ? 'any' : undefined}
- type={inputType}
- value={editable && typeof customValue === 'string' ? customValue : ''}
- placeholder={placeholder}
- disabled={!editable}
- autoComplete="off"
- onChange={(event) =>
- updateSelection({
- ...selection,
- customValue: event.target.value,
- })
- }
- />
- )}
- {slot.description && (
- <p id={descriptionId} className="system-xs-regular text-text-tertiary">
- {slot.description}
- </p>
- )}
- {error && (
- <p id={errorId} role="alert" className="system-xs-regular text-text-destructive">
- {error}
- </p>
- )}
+ ) : null}
+ <Field name={inputId} className="contents">
+ {!isLLM && (
+ <Input
+ id={inputId}
+ step={inputType === 'number' ? 'any' : undefined}
+ type={inputType}
+ value={editable && typeof customValue === 'string' ? customValue : ''}
+ placeholder={placeholder}
+ disabled={!editable}
+ autoComplete="off"
+ onChange={(event) =>
+ updateSelection({
+ ...selection,
+ customValue: event.target.value,
+ })
+ }
+ />
+ )}
+ {slot.description && (
+ <FieldDescription id={descriptionId}>{slot.description}</FieldDescription>
+ )}
+ <FieldError id={errorId} />
+ </Field>
</fieldset>
)
},
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/environment-variables-section.tsx b/web/app/components/app/deploy/shared/deployment-configuration/environment-variables-section.tsx
index 54f3864193e..c6559db0fd1 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/environment-variables-section.tsx
+++ b/web/app/components/app/deploy/shared/deployment-configuration/environment-variables-section.tsx
@@ -1,22 +1,18 @@
import type { EnvironmentVariableGroup } from '@dify/contracts/enterprise-app-deploy/types.gen'
import type { DeploymentConfigurationValuesController } from './use-deployment-configuration-values'
-import type { DeploymentFieldError } from './utils/field-id'
import { cn } from '@langgenius/dify-ui/cn'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import { EnvironmentVariableField } from './environment-variable-field'
import { SectionHeading } from './section-heading'
-import { environmentVariableFieldId } from './utils/field-id'
import { SubworkflowSourceTitle, WorkflowReferenceIcon } from './workflow-source-popover'
function EnvironmentVariableGroupFields({
group,
- fieldError,
getEnvironmentVariableSelection,
setEnvironmentVariableSelection,
}: {
group: EnvironmentVariableGroup
- fieldError?: DeploymentFieldError
getEnvironmentVariableSelection: DeploymentConfigurationValuesController['getEnvironmentVariableSelection']
setEnvironmentVariableSelection: DeploymentConfigurationValuesController['setEnvironmentVariableSelection']
}) {
@@ -42,11 +38,6 @@ function EnvironmentVariableGroupFields({
<div className="flex min-w-0 flex-1 flex-col gap-4">
{group.environment_variable_slots.map((slot) => (
<EnvironmentVariableField
- error={
- fieldError?.fieldId === environmentVariableFieldId(owner.workflow_id, slot.key)
- ? fieldError.message
- : undefined
- }
key={`${owner.workflow_id}:${slot.key}:${slot.has_configured_value}:${slot.has_last_deployed_value}`}
slot={slot}
workflowId={owner.workflow_id}
@@ -63,14 +54,12 @@ function EnvironmentVariableGroupFields({
export const EnvironmentVariablesSection = memo(
({
environmentVariableGroups,
- fieldError,
getEnvironmentVariableSelection,
hasCredentialSlots,
horizontalPaddingClassName,
setEnvironmentVariableSelection,
}: {
environmentVariableGroups: EnvironmentVariableGroup[]
- fieldError?: DeploymentFieldError
getEnvironmentVariableSelection: DeploymentConfigurationValuesController['getEnvironmentVariableSelection']
hasCredentialSlots: boolean
horizontalPaddingClassName: string
@@ -101,7 +90,6 @@ export const EnvironmentVariablesSection = memo(
return (
<EnvironmentVariableGroupFields
- fieldError={fieldError}
key={owner.workflow_id}
group={group}
getEnvironmentVariableSelection={getEnvironmentVariableSelection}
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/index.tsx b/web/app/components/app/deploy/shared/deployment-configuration/index.tsx
index 5edd2920ecb..bdb51c5cf1b 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/index.tsx
+++ b/web/app/components/app/deploy/shared/deployment-configuration/index.tsx
@@ -5,6 +5,7 @@ import type { DeploymentVersion } from '../../utils/version'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { DialogClose, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { Form } from '@langgenius/dify-ui/form'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useTranslation } from 'react-i18next'
import { DeploymentConfigurationContent } from './content'
@@ -43,7 +44,7 @@ export function DeploymentConfiguration({
environmentId: request.environmentId,
workflowId: version.id,
})
- const { canDeploy, clearFieldError, fieldError, formRef, handleSubmit, isDeploying } =
+ const { canDeploy, clearFieldError, fieldErrors, formRef, handleSubmit, isDeploying } =
useDeploymentConfigurationForm({
appId,
configurationValues,
@@ -57,7 +58,12 @@ export function DeploymentConfiguration({
})
return (
- <form ref={formRef} className="flex min-h-0 flex-1 flex-col" onSubmit={handleSubmit}>
+ <Form
+ ref={formRef}
+ className="flex min-h-0 flex-1 flex-col"
+ errors={fieldErrors}
+ onSubmit={handleSubmit}
+ >
{!embedded && (
<DialogClose
render={
@@ -101,7 +107,6 @@ export function DeploymentConfiguration({
<DeploymentConfigurationContent
compact={embedded}
configurationValues={configurationValues}
- fieldError={fieldError}
onConfigurationChange={clearFieldError}
queryState={queryState}
request={request}
@@ -127,6 +132,6 @@ export function DeploymentConfiguration({
{tCommon(($) => $['appMenus.deploy'])}
</Button>
</footer>
- </form>
+ </Form>
)
}
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-form.ts b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-form.ts
index 9deca84cb44..99b0dc3dfc2 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-form.ts
+++ b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-form.ts
@@ -4,7 +4,7 @@ import type { SubmitEventHandler } from 'react'
import type { DeploymentConfigurationQueryState } from './use-deployment-configuration-queries'
import type { DeploymentConfigurationValuesController } from './use-deployment-configuration-values'
import type { DeploymentFieldError } from './utils/field-id'
-import { useLayoutEffect, useRef, useState } from 'react'
+import { useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { useDeployWorkflow } from '../../hooks/use-deploy-workflow'
@@ -41,7 +41,12 @@ export function useDeploymentConfigurationForm({
const { t: tDeployments } = useTranslation(['deployments'])
const { t: tWorkflow } = useTranslation(['workflow'])
const [fieldError, setFieldError] = useState<DeploymentFieldError>()
+ const fieldErrors = useMemo(
+ () => fieldError && { [fieldError.fieldId]: fieldError.message },
+ [fieldError],
+ )
const formRef = useRef<HTMLFormElement | null>(null)
+ // `Form` focuses invalid fields with a registered control; the LLM value group has none.
useLayoutEffect(() => {
if (fieldError)
formRef.current?.querySelector<HTMLElement>(`[id="${fieldError.fieldId}"]`)?.focus()
@@ -115,7 +120,7 @@ export function useDeploymentConfigurationForm({
return {
canDeploy,
clearFieldError: () => setFieldError(undefined),
- fieldError,
+ fieldErrors,
formRef,
handleSubmit,
isDeploying: deployMutation.isPending,
diff --git a/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-values.ts b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-values.ts
index 3122ad586a1..5d3e2382367 100644
--- a/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-values.ts
+++ b/web/app/components/app/deploy/shared/deployment-configuration/use-deployment-configuration-values.ts
@@ -2,7 +2,7 @@
import type { EnvVarValueSource } from '@dify/contracts/enterprise-app-deploy/types.gen'
import type { LLMEnvironmentVariableValue } from '@/app/components/workflow/types'
-import { useCallback, useRef, useState } from 'react'
+import { useCallback, useRef } from 'react'
export type EnvironmentVariableSelection = {
customValue: string | LLMEnvironmentVariableValue
@@ -15,7 +15,7 @@ export type DeploymentConfigurationValues = {
}
export type DeploymentConfigurationValuesController = {
- credentials: DeploymentConfigurationValues['credentials']
+ getCredential: (key: string) => string | undefined
getEnvironmentVariableSelection: (
workflowId: string,
key: string,
@@ -38,7 +38,7 @@ export function useDeploymentConfigurationValues() {
credentials: {},
environmentVariables: {},
})
- const [credentials, setCredentials] = useState<DeploymentConfigurationValues['credentials']>({})
+ const getCredential = useCallback((key: string) => valuesRef.current.credentials[key], [])
const getEnvironmentVariableSelection = useCallback(
(workflowId: string, key: string) =>
@@ -50,15 +50,13 @@ export function useDeploymentConfigurationValues() {
const current = valuesRef.current
if (current.credentials[key] === value) return
- const nextCredentials = {
- ...current.credentials,
- [key]: value,
- }
valuesRef.current = {
...current,
- credentials: nextCredentials,
+ credentials: {
+ ...current.credentials,
+ [key]: value,
+ },
}
- setCredentials(nextCredentials)
}, [])
const setEnvironmentVariableSelection = useCallback(
(workflowId: string, key: string, value: EnvironmentVariableSelection) => {
@@ -75,7 +73,7 @@ export function useDeploymentConfigurationValues() {
)
return {
- credentials,
+ getCredential,
getEnvironmentVariableSelection,
getValues,
setCredential,
diff --git a/web/app/components/datasets/external-api/external-api-modal/Form.tsx b/web/app/components/datasets/external-api/external-api-modal/Form.tsx
index 5916bacc1d7..14b19c92a22 100644
--- a/web/app/components/datasets/external-api/external-api-modal/Form.tsx
+++ b/web/app/components/datasets/external-api/external-api-modal/Form.tsx
@@ -1,13 +1,15 @@
import type { FC, SubmitEventHandler } from 'react'
import type { CreateExternalAPIReq, FormSchema } from '../declarations'
import { cn } from '@langgenius/dify-ui/cn'
+import { Field, FieldError } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { RiBookOpenLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
-type FormProps = {
+type ExternalAPIFormProps = {
id: string
onSubmit: SubmitEventHandler<HTMLFormElement>
className?: string
@@ -20,7 +22,7 @@ type FormProps = {
errors?: Partial<Record<'api_key' | 'endpoint' | 'name', string>>
}
-const Form: FC<FormProps> = React.memo(
+const ExternalAPIForm: FC<ExternalAPIFormProps> = React.memo(
({
id,
onSubmit,
@@ -56,14 +58,9 @@ const Form: FC<FormProps> = React.memo(
variable === 'name'
? value[variable]
: value.settings[variable as keyof typeof value.settings] || ''
- const fieldError = errors?.[variable as keyof typeof errors]
- const errorId = `${variable}-error`
return (
- <div
- key={variable}
- className={cn(itemClassName, 'flex flex-col items-start gap-1 self-stretch')}
- >
+ <Field key={variable} name={variable} className={cn(itemClassName, 'self-stretch')}>
<div className="flex w-full items-center justify-between">
<label
className={cn(fieldLabelClassName, 'system-sm-semibold text-text-secondary')}
@@ -91,35 +88,29 @@ const Form: FC<FormProps> = React.memo(
placeholder={t(($) => $['placeholder.input'], { ns: 'common' }) || ''}
spellCheck={variable === 'endpoint' || type === 'secret' ? false : undefined}
id={variable}
- name={variable}
- aria-describedby={fieldError ? errorId : undefined}
- aria-invalid={Boolean(fieldError)}
value={fieldValue}
onChange={(val) => handleFormChange(variable, val.target.value)}
required={required}
className={cn(inputClassName)}
/>
- {fieldError && (
- <p id={errorId} className="system-xs-regular text-text-destructive" role="alert">
- {fieldError}
- </p>
- )}
- </div>
+ <FieldError />
+ </Field>
)
}
return (
- <form
+ <Form
id={id}
+ errors={errors}
onSubmit={onSubmit}
className={cn('flex flex-col items-start justify-center gap-4 self-stretch', className)}
>
{formSchemas.map((formSchema) => renderField(formSchema))}
- </form>
+ </Form>
)
},
)
-Form.displayName = 'Form'
+ExternalAPIForm.displayName = 'ExternalAPIForm'
-export default Form
+export default ExternalAPIForm
diff --git a/web/app/components/datasets/external-api/external-api-modal/__tests__/Form.spec.tsx b/web/app/components/datasets/external-api/external-api-modal/__tests__/Form.spec.tsx
index e026253c39a..ab577c1f396 100644
--- a/web/app/components/datasets/external-api/external-api-modal/__tests__/Form.spec.tsx
+++ b/web/app/components/datasets/external-api/external-api-modal/__tests__/Form.spec.tsx
@@ -3,7 +3,7 @@ import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import Form from '../Form'
+import ExternalAPIForm from '../Form'
vi.mock('@/context/i18n', () => ({
useDocLink: () => (path: string) => `https://docs.example.com${path}`,
@@ -11,7 +11,7 @@ vi.mock('@/context/i18n', () => ({
// Mock context for i18n doc link
-describe('Form', () => {
+describe('ExternalAPIForm', () => {
const defaultFormSchemas: FormSchema[] = [
{
variable: 'name',
@@ -59,7 +59,7 @@ describe('Form', () => {
const Harness = () => {
const [value, setValue] = useState(defaultValue)
return (
- <Form
+ <ExternalAPIForm
{...defaultProps}
value={value}
onChange={(next) => {
diff --git a/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx b/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx
index 6043394f334..f30810babd0 100644
--- a/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx
@@ -62,9 +62,8 @@ it('shows one localized field error and does not request an invalid endpoint', a
await user.type(endpointInput, 'not-a-url')
await user.type(screen.getByLabelText(/API Key/), 'key12345')
await user.click(save())
- const alerts = await screen.findAllByRole('alert')
- expect(alerts).toHaveLength(1)
- expect(alerts[0]).toHaveTextContent('dataset.validation.invalidHttpUrl')
+ await waitFor(() => expect(endpointInput).toHaveFocus())
+ expect(screen.getAllByText('dataset.validation.invalidHttpUrl')).toHaveLength(1)
expect(endpointInput).toHaveAttribute('aria-invalid', 'true')
expect(endpointInput).toHaveAccessibleDescription('dataset.validation.invalidHttpUrl')
expect(createExternalAPI).not.toHaveBeenCalled()
diff --git a/web/app/components/datasets/external-api/external-api-modal/index.tsx b/web/app/components/datasets/external-api/external-api-modal/index.tsx
index 72cc12ee308..d7b7d5c56d9 100644
--- a/web/app/components/datasets/external-api/external-api-modal/index.tsx
+++ b/web/app/components/datasets/external-api/external-api-modal/index.tsx
@@ -28,7 +28,7 @@ import { useTranslation } from 'react-i18next'
import { EncryptedBottom } from '@/app/components/base/encrypted-bottom'
import { toast } from '@/app/notifications'
import { createExternalAPI } from '@/service/datasets'
-import Form from './Form'
+import ExternalAPIForm from './Form'
type AddExternalAPIModalProps = {
data?: CreateExternalAPIReq
@@ -215,7 +215,7 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
</DialogHeader>
<DialogBody>
- <Form
+ <ExternalAPIForm
id={formId}
value={formData}
onChange={handleDataChange}
diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-content/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-content/__tests__/index.spec.tsx
index 6768bbd47d6..3b3ef8ef66d 100644
--- a/web/app/components/header/account-setting/members-page/edit-workspace-content/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/edit-workspace-content/__tests__/index.spec.tsx
@@ -153,7 +153,7 @@ describe('EditWorkspaceContent', () => {
expect(getSaveButton()).toBeDisabled()
expect(input).toHaveAttribute('aria-invalid', 'true')
- expect(screen.getByRole('alert')).toBeInTheDocument()
+ expect(input).toHaveAccessibleDescription(/common\.errorMsg\.fieldRequired/)
})
it('should not submit when the form is submitted while save is disabled', async () => {
diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-content/index.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-content/index.tsx
index 9654bf13f0a..90582824e79 100644
--- a/web/app/components/header/account-setting/members-page/edit-workspace-content/index.tsx
+++ b/web/app/components/header/account-setting/members-page/edit-workspace-content/index.tsx
@@ -1,7 +1,6 @@
'use client'
import type { Ref } from 'react'
import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
import {
DialogBody,
DialogClose,
@@ -10,6 +9,7 @@ import {
DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
+import { Field, FieldError } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
import { useAtomValue } from 'jotai'
import { useId, useMemo, useState } from 'react'
@@ -29,7 +29,6 @@ const EditWorkspaceContent = ({ inputRef }: IEditWorkspaceContentProps) => {
const [name, setName] = useState<string>(currentWorkspace.name)
const [isSubmitting, setIsSubmitting] = useState(false)
const inputId = useId()
- const errorId = useId()
const saveButtonLabelId = useId()
const normalizedName = name.trim()
const hasChanges = normalizedName !== currentWorkspace.name
@@ -78,34 +77,26 @@ const EditWorkspaceContent = ({ inputRef }: IEditWorkspaceContentProps) => {
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
</DialogHeader>
- <DialogBody className="space-y-2">
- <label htmlFor={inputId} className="block text-sm font-medium text-text-primary">
- {t(($) => $['account.workspaceName'], { ns: 'accountSettings' })}
- </label>
- <Input
- ref={inputRef}
- id={inputId}
- value={name}
- placeholder={t(($) => $['account.workspaceNamePlaceholder'], {
- ns: 'accountSettings',
- })}
- onChange={(e) => {
- setName(e.target.value)
- }}
- aria-invalid={hasError}
- aria-describedby={hasError ? errorId : undefined}
- className={cn(
- hasError &&
- 'border-components-input-border-destructive bg-components-input-bg-destructive hover:border-components-input-border-destructive hover:bg-components-input-bg-destructive focus:border-components-input-border-destructive focus:bg-components-input-bg-destructive',
- )}
- />
- <div className="min-h-6">
- {hasError && (
- <p id={errorId} className="system-xs-regular text-text-destructive" role="alert">
- {nameErrorMessage}
- </p>
- )}
- </div>
+ <DialogBody>
+ <Field invalid={hasError} className="gap-2">
+ <label htmlFor={inputId} className="block text-sm font-medium text-text-primary">
+ {t(($) => $['account.workspaceName'], { ns: 'accountSettings' })}
+ </label>
+ <Input
+ ref={inputRef}
+ id={inputId}
+ value={name}
+ placeholder={t(($) => $['account.workspaceNamePlaceholder'], {
+ ns: 'accountSettings',
+ })}
+ onChange={(e) => {
+ setName(e.target.value)
+ }}
+ />
+ <div className="min-h-6">
+ <FieldError match={hasError}>{nameErrorMessage}</FieldError>
+ </div>
+ </Field>
</DialogBody>
<DialogFooter>
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 1af990ff6ee..5d46ed945b6 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
@@ -2,7 +2,7 @@
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 { 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 { useQuery } from '@tanstack/react-query'
@@ -10,7 +10,7 @@ import { produce } from 'immer'
import * as React 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 ConfigField from '@/app/components/app/configuration/config-var/config-modal/field'
import { getFileSizeLimit } from '@/app/components/base/file-uploader/hooks'
import { consoleQuery } from '@/service/console'
import { TransferMethod } from '@/types/app'
@@ -132,9 +132,9 @@ const FileUploadSetting: FC<Props> = ({
)
return (
- <div>
+ <div className="flex flex-col gap-4">
{!inFeaturePanel && (
- <Field
+ <ConfigField
title={t(($) => $['variableConfig.file.supportFileTypes'], { ns: 'appDebug' })}
errorMessage={validationError?.message}
errorId={errorId}
@@ -170,9 +170,9 @@ const FileUploadSetting: FC<Props> = ({
customFileTypesErrorId={customFileTypesErrorId}
/>
</div>
- </Field>
+ </ConfigField>
)}
- <FormField className="mt-4">
+ <Field>
<Fieldset
className="flex flex-col items-stretch gap-0"
render={
@@ -203,12 +203,9 @@ const FileUploadSetting: FC<Props> = ({
))}
</div>
</Fieldset>
- </FormField>
+ </Field>
{isMultiple && (
- <Field
- className="mt-4"
- title={t(($) => $['variableConfig.maxNumberOfUploads'], { ns: 'appDebug' })!}
- >
+ <ConfigField title={t(($) => $['variableConfig.maxNumberOfUploads'], { ns: 'appDebug' })!}>
<div>
<div className="mb-1.5 body-xs-regular text-text-tertiary">
{t(($) => $['variableConfig.maxNumberTip'], {
@@ -229,12 +226,11 @@ const FileUploadSetting: FC<Props> = ({
onChange={handleMaxUploadNumLimitChange}
/>
</div>
- </Field>
+ </ConfigField>
)}
{inFeaturePanel && !hideSupportFileType && (
- <Field
+ <ConfigField
title={t(($) => $['variableConfig.file.supportFileTypes'], { ns: 'appDebug' })}
- className="mt-4"
errorMessage={validationError?.message}
errorId={errorId}
>
@@ -269,7 +265,7 @@ const FileUploadSetting: FC<Props> = ({
customFileTypesErrorId={customFileTypesErrorId}
/>
</div>
- </Field>
+ </ConfigField>
)}
</div>
)
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx
index b4fac214319..ed9f978542d 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx
@@ -10,7 +10,7 @@ import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import { Switch } from '@langgenius/dify-ui/switch'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
-import { useId, useRef, useState } from 'react'
+import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { OutputTypeSelect } from './type-select'
import {
@@ -55,7 +55,6 @@ export function OutputEditCard({
onConfirm: (output: DeclaredOutputConfig, state: EditingState) => void
}) {
const { t } = useTranslation(['common', 'workflowAgent'])
- const nameErrorId = useId()
const editorRef = useRef<HTMLFormElement>(null)
const [draft, setDraft] = useState(state.draft)
const trimmedName = draft.name.trim()
@@ -119,13 +118,12 @@ export function OutputEditCard({
}}
>
<div className="px-2 pt-2">
- <div className="flex h-6 items-center gap-x-2">
+ <div className="grid grid-cols-[repeat(3,auto)] items-center justify-start gap-x-2 gap-y-1">
<Field name="name" invalid={hasNameError} className="contents">
<FieldLabel className="sr-only">
{t(($) => $['nodes.agent.outputVars.nameLabel'], { ns: 'workflowAgent' })}
</FieldLabel>
<Input
- aria-describedby={hasNameError ? nameErrorId : undefined}
// oxlint-disable-next-line jsx-a11y/no-autofocus -- Inline editor opens from an explicit user action and should focus the first editable field.
autoFocus
required
@@ -137,6 +135,13 @@ export function OutputEditCard({
className="h-6 w-24 rounded-md px-1.5 py-0 code-sm-semibold"
onChange={(event) => updateDraft({ name: event.currentTarget.value })}
/>
+ {hasNameError && (
+ <FieldError match className="col-span-full row-start-2 px-1">
+ {duplicateName
+ ? t(($) => $['nodes.agent.outputVars.nameDuplicate'], { ns: 'workflowAgent' })
+ : t(($) => $['nodes.agent.outputVars.nameInvalid'], { ns: 'workflowAgent' })}
+ </FieldError>
+ )}
</Field>
<OutputTypeSelect value={draft.type} onChange={(value) => updateDraft({ type: value })} />
<Field name="required" className="contents">
@@ -150,19 +155,6 @@ export function OutputEditCard({
</FieldLabel>
</Field>
</div>
- {hasNameError && (
- <Field name="nameError" invalid className="contents">
- <FieldError
- id={nameErrorId}
- match
- className="mt-1 px-1 py-0 system-xs-regular text-text-destructive"
- >
- {duplicateName
- ? t(($) => $['nodes.agent.outputVars.nameDuplicate'], { ns: 'workflowAgent' })
- : t(($) => $['nodes.agent.outputVars.nameInvalid'], { ns: 'workflowAgent' })}
- </FieldError>
- </Field>
- )}
<Field name="description" className="contents">
<FieldLabel className="sr-only">
{t(($) => $['nodes.agent.outputVars.descriptionLabel'], { ns: 'workflowAgent' })}
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template.spec.tsx
index 617dd60b7a5..322f057c452 100644
--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template.spec.tsx
@@ -237,7 +237,9 @@ describe('Human Input v2 Message Template', () => {
await setBody('')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(screen.getAllByRole('alert')).toHaveLength(2)
+ expect(
+ screen.getByLabelText('workflow.nodes.humanInputV2.template.subject'),
+ ).toHaveAccessibleDescription('workflow.nodes.humanInputV2.error.subjectRequired')
expect(screen.getByText('workflow.nodes.humanInputV2.error.bodyRequired')).toBeInTheDocument()
expect(props.onChange).not.toHaveBeenCalled()
diff --git a/web/app/components/workflow/nodes/human-input-v2/components/message-template.tsx b/web/app/components/workflow/nodes/human-input-v2/components/message-template.tsx
index 260bbb513df..00e04db20b5 100644
--- a/web/app/components/workflow/nodes/human-input-v2/components/message-template.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/components/message-template.tsx
@@ -5,6 +5,7 @@ import type { HumanInputV2MessageTemplate } from '../types'
import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { Field, FieldError } from '@langgenius/dify-ui/field'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Input } from '@langgenius/dify-ui/input'
@@ -345,10 +346,10 @@ const MessageTemplate = ({
</IconButton>
</header>
<div className="max-h-[60vh] min-h-[260px] space-y-5 overflow-y-auto px-6 py-3">
- <div>
+ <Field invalid={errors.subject}>
<label
htmlFor={`${nodeId}-message-subject`}
- className="mb-1 flex h-6 items-center system-sm-medium text-text-secondary"
+ className="flex h-6 items-center system-sm-medium text-text-secondary"
>
{t(($) => $['nodes.humanInputV2.template.subject'], { ns: 'workflow' })}
</label>
@@ -356,8 +357,6 @@ const MessageTemplate = ({
id={`${nodeId}-message-subject`}
value={draft.subject}
disabled={readonly || pending}
- aria-invalid={errors.subject}
- aria-describedby={errors.subject ? `${nodeId}-message-subject-error` : undefined}
onChange={(event) => {
resetTestResult()
setDraft((current) => ({ ...current, subject: event.target.value }))
@@ -366,16 +365,10 @@ const MessageTemplate = ({
ns: 'workflow',
})}
/>
- {errors.subject && (
- <div
- id={`${nodeId}-message-subject-error`}
- role="alert"
- className="mt-1 system-xs-regular text-text-destructive"
- >
- {t(($) => $['nodes.humanInputV2.error.subjectRequired'], { ns: 'workflow' })}
- </div>
- )}
- </div>
+ <FieldError match={errors.subject}>
+ {t(($) => $['nodes.humanInputV2.error.subjectRequired'], { ns: 'workflow' })}
+ </FieldError>
+ </Field>
<MessageTemplateBody
nodeId={nodeId}
readOnly={readonly || pending}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/classic-settings.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/classic-settings.tsx
index d1d48b43f0d..cd626857521 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/classic-settings.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/classic-settings.tsx
@@ -12,7 +12,7 @@ import type { AgentKnowledgeRetrievalItem } from '@/features/agent-v2/agent-comp
import type { KnowledgeValidationResult } from '@/features/agent-v2/agent-composer/knowledge-validation'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { FieldLabel, Field as FormField } from '@langgenius/dify-ui/field'
+import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { RadioGroup, RadioItem } from '@langgenius/dify-ui/radio-group'
import { Textarea } from '@langgenius/dify-ui/textarea'
@@ -22,7 +22,7 @@ import { useId, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
-import Field from '@/app/components/workflow/nodes/_base/components/field'
+import WorkflowField from '@/app/components/workflow/nodes/_base/components/field'
import AddKnowledge from '@/app/components/workflow/nodes/knowledge-retrieval/components/add-dataset'
import {
comparisonOperatorNotRequireValue,
@@ -214,34 +214,36 @@ function ClassicSettingsFields({
)
return (
<div className="flex min-h-0 flex-1 flex-col gap-1 py-2">
- <div className="flex flex-col gap-1 py-2">
- <div id={queryModeLabelId} className="system-sm-medium text-text-secondary">
- {t(($) => $['agentDetail.configure.knowledgeRetrieval.dialog.query.label'])}
+ <div className="flex flex-col gap-2 py-2">
+ <div className="flex flex-col gap-1">
+ <div id={queryModeLabelId} className="system-sm-medium text-text-secondary">
+ {t(($) => $['agentDetail.configure.knowledgeRetrieval.dialog.query.label'])}
+ </div>
+ <RadioGroup<KnowledgeRetrievalQueryMode>
+ aria-labelledby={queryModeLabelId}
+ className="w-full gap-2"
+ value={queryMode}
+ onValueChange={(nextMode) => {
+ if (nextMode) onChange({ queryMode: nextMode })
+ }}
+ >
+ {queryModeOptions.map((mode) => (
+ <RadioItem<KnowledgeRetrievalQueryMode>
+ key={mode}
+ value={mode}
+ nativeButton
+ render={<button type="button" className={optionCardClassName} />}
+ >
+ <span className="min-w-0 truncate">
+ {t(($) => $[`agentDetail.configure.knowledgeRetrieval.dialog.query.${mode}`])}
+ </span>
+ </RadioItem>
+ ))}
+ </RadioGroup>
</div>
- <RadioGroup<KnowledgeRetrievalQueryMode>
- aria-labelledby={queryModeLabelId}
- className="w-full gap-2"
- value={queryMode}
- onValueChange={(nextMode) => {
- if (nextMode) onChange({ queryMode: nextMode })
- }}
- >
- {queryModeOptions.map((mode) => (
- <RadioItem<KnowledgeRetrievalQueryMode>
- key={mode}
- value={mode}
- nativeButton
- render={<button type="button" className={optionCardClassName} />}
- >
- <span className="min-w-0 truncate">
- {t(($) => $[`agentDetail.configure.knowledgeRetrieval.dialog.query.${mode}`])}
- </span>
- </RadioItem>
- ))}
- </RadioGroup>
{queryMode === 'custom' ? (
<>
- <FormField className="pt-1">
+ <Field invalid={Boolean(queryError)}>
<FieldLabel>
{t(
($) =>
@@ -253,7 +255,6 @@ function ClassicSettingsFields({
($) =>
$['agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel'],
)}
- aria-invalid={queryError ? true : undefined}
className="h-20 resize-none rounded-lg px-3 py-2 system-sm-regular"
placeholder={t(
($) =>
@@ -262,27 +263,24 @@ function ClassicSettingsFields({
value={customQuery}
onValueChange={(nextQuery) => onChange({ customQuery: nextQuery })}
/>
- </FormField>
- <p className="system-xs-regular text-text-tertiary">
- {t(
- ($) => $['agentDetail.configure.knowledgeRetrieval.dialog.query.customDescription'],
- )}
- </p>
- {queryError && (
- <p role="alert" className="system-xs-regular text-text-destructive">
- {queryError}
- </p>
- )}
+ <FieldDescription>
+ {t(
+ ($) =>
+ $['agentDetail.configure.knowledgeRetrieval.dialog.query.customDescription'],
+ )}
+ </FieldDescription>
+ <FieldError match={Boolean(queryError)}>{queryError}</FieldError>
+ </Field>
</>
) : (
- <p className="pt-1 system-xs-regular text-text-tertiary">
+ <p className="system-xs-regular text-text-tertiary">
{t(($) => $['agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription'])}
</p>
)}
</div>
<div className="py-2">
- <Field
+ <WorkflowField
title={t(($) => $['agentDetail.configure.knowledgeRetrieval.dialog.knowledge.label'])}
required
operations={
@@ -370,7 +368,7 @@ function ClassicSettingsFields({
</div>
)}
</>
- </Field>
+ </WorkflowField>
</div>
{/* The shared workflow filter brings its own px-4 gutter; cancel it to line up with the fields above. */}
diff --git a/web/features/contacts/management/__tests__/external-contact-dialog.spec.tsx b/web/features/contacts/management/__tests__/external-contact-dialog.spec.tsx
index 130ec0bec49..29a45cf3017 100644
--- a/web/features/contacts/management/__tests__/external-contact-dialog.spec.tsx
+++ b/web/features/contacts/management/__tests__/external-contact-dialog.spec.tsx
@@ -384,9 +384,8 @@ describe('ExternalContactDialog pending state', () => {
await user.paste('中'.repeat(256))
await user.click(save)
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'contacts.external.validation.name_too_long',
- )
+ await waitFor(() => expect(name).toHaveFocus())
+ expect(name).toHaveAccessibleDescription(/contacts\.external\.validation\.name_too_long/)
expect(name).toHaveAttribute('aria-invalid', 'true')
expect(contacts.external.post).not.toHaveBeenCalled()
expect(contacts.external.byContactId.patch).not.toHaveBeenCalled()
diff --git a/web/features/contacts/management/external-contact-dialog.tsx b/web/features/contacts/management/external-contact-dialog.tsx
index 093308992db..34e0e114fe9 100644
--- a/web/features/contacts/management/external-contact-dialog.tsx
+++ b/web/features/contacts/management/external-contact-dialog.tsx
@@ -297,7 +297,14 @@ export function ExternalContactDialog({
{t(($) => $[contact ? 'external.editDescription' : 'external.description'])}
</DialogDescription>
</div>
- <Form<ExternalContactDraft> onFormSubmit={handleSubmit}>
+ <Form<ExternalContactDraft>
+ errors={
+ fieldError && fieldErrorMessage
+ ? { [nameError ? 'displayName' : 'email']: fieldErrorMessage }
+ : undefined
+ }
+ onFormSubmit={handleSubmit}
+ >
<div className="relative flex flex-col items-center gap-2 px-4 pt-10 pb-2">
<div
aria-hidden
@@ -370,10 +377,9 @@ export function ExternalContactDialog({
)}
</div>
<div className="space-y-4 px-6 py-3">
- <Field name="displayName" invalid={nameError}>
+ <Field name="displayName">
<FieldLabel>{t(($) => $['external.name'])}</FieldLabel>
<Input
- aria-describedby={nameError ? 'external-name-error' : undefined}
autoComplete="name"
placeholder={t(($) => $['external.namePlaceholder'])}
disabled={busy}
@@ -381,28 +387,14 @@ export function ExternalContactDialog({
value={draft.displayName}
onChange={(event) => updateDraft('displayName', event.currentTarget.value)}
/>
- {nameError && (
- <p
- id="external-name-error"
- role="alert"
- className="body-xs-regular text-text-destructive"
- >
- {fieldErrorMessage}
- </p>
- )}
+ {nameError && <FieldError match>{fieldErrorMessage}</FieldError>}
<FieldError match="valueMissing">
{t(($) => $['external.validation.name_required'])}
</FieldError>
</Field>
- <Field
- name="email"
- invalid={fieldError === 'email_required' || fieldError === 'email_invalid'}
- >
+ <Field name="email">
<FieldLabel>{t(($) => $['external.email'])}</FieldLabel>
<Input
- aria-describedby={
- fieldError?.startsWith('email') ? 'external-email-error' : undefined
- }
autoComplete="email"
placeholder={t(($) => $['external.email'])}
disabled={busy}
@@ -412,13 +404,7 @@ export function ExternalContactDialog({
onChange={(event) => updateDraft('email', event.currentTarget.value)}
/>
{fieldError?.startsWith('email') && (
- <p
- id="external-email-error"
- role="alert"
- className="body-xs-regular text-text-destructive"
- >
- {fieldErrorMessage}
- </p>
+ <FieldError match>{fieldErrorMessage}</FieldError>
)}
<FieldError match="valueMissing">
{t(($) => $['external.validation.email_required'])}
diff --git a/web/features/human-input/form/loaded-form-content.tsx b/web/features/human-input/form/loaded-form-content.tsx
index daa88f553f5..b7290fb3483 100644
--- a/web/features/human-input/form/loaded-form-content.tsx
+++ b/web/features/human-input/form/loaded-form-content.tsx
@@ -1,9 +1,11 @@
-import type { ComponentPropsWithoutRef, ReactNode } from 'react'
+import type { FormProps } from '@langgenius/dify-ui/form'
+import type { ComponentPropsWithoutRef, ReactNode, SubmitEventHandler } from 'react'
import type { HumanInputFormDefinition } from './types'
import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
import type { UnsubmittedHumanInputContentProps } from '@/app/components/base/chat/chat/answer/human-input-content/type'
import type { MarkdownProps } from '@/app/components/base/markdown'
import { Button } from '@langgenius/dify-ui/button'
+import { Form } from '@langgenius/dify-ui/form'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -30,6 +32,7 @@ type LoadedFormContentProps = {
isSubmitting: boolean
actionsDisabled?: boolean
verificationContent?: ReactNode
+ errors?: FormProps['errors']
onSubmit: (inputs: Record<string, unknown>, actionID: string) => void | Promise<void>
}
@@ -211,6 +214,7 @@ const FormBody = ({
isSubmitting,
actionsDisabled = false,
verificationContent,
+ errors,
onSubmit,
layout = 'standalone',
}: FormBodyProps) => {
@@ -246,12 +250,21 @@ const FormBody = ({
setPending(false)
}
}
+ const handleSubmit: SubmitEventHandler<HTMLFormElement> = (event) => {
+ event.preventDefault()
+ const submitter = event.nativeEvent.submitter
+ if (submitter instanceof HTMLButtonElement && submitter.value) void submit(submitter.value)
+ }
const hasInvalidInput = compact ? hasInvalidSelectOrFileInput : hasInvalidRequiredHumanInput
const disabled =
actionsDisabled || isSubmitting || pending || hasInvalidInput(renderedFormInputs, inputs)
return (
- <div className={compact ? 'flex flex-col gap-2' : 'flex flex-col gap-3'}>
+ <Form
+ className={compact ? 'flex flex-col gap-2' : 'flex flex-col gap-3'}
+ errors={errors}
+ onSubmit={handleSubmit}
+ >
{contentList.map(({ key, content }) => {
const match = /\{\{#\$output\.([^#]+)#\}\}/.exec(content)
if (!match) {
@@ -294,16 +307,18 @@ const FormBody = ({
{definition.actions.map((action) => (
<Button
key={action.id}
+ type="submit"
+ name="action"
+ value={action.id}
size={compact ? 'small' : 'medium'}
disabled={disabled}
variant={getButtonStyle(action.button_style)}
- onClick={() => submit(action.id)}
>
{action.title}
</Button>
))}
</div>
- </div>
+ </Form>
)
}
@@ -348,6 +363,7 @@ const LoadedFormContent = ({
isSubmitting,
actionsDisabled = false,
verificationContent,
+ errors,
onSubmit,
}: LoadedFormContentProps) => {
const branding = definition.branding
@@ -373,6 +389,7 @@ const LoadedFormContent = ({
isSubmitting={isSubmitting}
actionsDisabled={actionsDisabled}
verificationContent={verificationContent}
+ errors={errors}
onSubmit={onSubmit}
/>
<div>
diff --git a/web/features/human-input/public/__tests__/form.spec.tsx b/web/features/human-input/public/__tests__/form.spec.tsx
index a7ca365ab62..d41f2e57fdd 100644
--- a/web/features/human-input/public/__tests__/form.spec.tsx
+++ b/web/features/human-input/public/__tests__/form.spec.tsx
@@ -78,7 +78,9 @@ describe('HumanInputV2Form', () => {
await user.type(otpInput, '000000')
await user.click(screen.getByRole('button', { name: 'Approve' }))
- expect(await screen.findByRole('alert')).toHaveTextContent('share.humanInputV2.invalidOtp')
+ await waitFor(() => expect(otpInput).toHaveFocus())
+ expect(otpInput).toHaveAccessibleDescription('share.humanInputV2.invalidOtp')
+ expect(otpInput).toHaveAttribute('aria-invalid', 'true')
expect(requestAccess).toHaveBeenCalledTimes(1)
expect(otpInput).toHaveValue('000000')
diff --git a/web/features/human-input/public/form.tsx b/web/features/human-input/public/form.tsx
index 3d266bddb74..06203b8c194 100644
--- a/web/features/human-input/public/form.tsx
+++ b/web/features/human-input/public/form.tsx
@@ -83,6 +83,13 @@ const HumanInputV2Form = ({ token, transport: injectedTransport, now }: HumanInp
}
}
+ const invalidOtp = state.error === 'invalid-otp'
+ const otpErrors = useMemo(
+ () =>
+ invalidOtp ? { otp: t(($) => $['humanInputV2.invalidOtp'], { ns: 'share' }) } : undefined,
+ [invalidOtp, t],
+ )
+
if (state.phase === 'loading-form') return <LoadingPlaceholder className="h-full" />
if (state.phase === 'success') {
@@ -139,11 +146,12 @@ const HumanInputV2Form = ({ token, transport: injectedTransport, now }: HumanInp
isSubmitting={state.phase === 'submitting'}
actionsDisabled={!session.canSubmit}
onSubmit={session.submit}
+ errors={otpErrors}
verificationContent={
<OtpVerification
otpCode={state.otpCode}
requesting={state.phase === 'requesting-otp'}
- error={verificationError}
+ error={invalidOtp ? undefined : verificationError}
secondsUntilResend={session.secondsUntilResend}
secondsUntilExpiry={session.secondsUntilExpiry}
hasChallenge={Boolean(state.challenge)}
diff --git a/web/features/human-input/public/otp-verification.tsx b/web/features/human-input/public/otp-verification.tsx
index 51649d51f36..f30166b4422 100644
--- a/web/features/human-input/public/otp-verification.tsx
+++ b/web/features/human-input/public/otp-verification.tsx
@@ -1,4 +1,5 @@
import { Button } from '@langgenius/dify-ui/button'
+import { Field, FieldError } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
import { useTranslation } from 'react-i18next'
@@ -28,36 +29,39 @@ const OtpVerification = ({
const { t } = useTranslation(['share'])
return (
- <div className="my-3 rounded-xl border border-divider-subtle bg-background-section p-3">
- <label htmlFor="human-input-v2-otp" className="system-sm-semibold text-text-primary">
- {t(($) => $['humanInputV2.otpLabel'], { ns: 'share' })}
- </label>
- <div className="mt-1 system-xs-regular text-text-secondary">
- {requesting
- ? t(($) => $['humanInputV2.requestingCode'], { ns: 'share' })
- : hasChallenge
- ? t(($) => $['humanInputV2.codeSent'], { ns: 'share' })
- : t(($) => $['humanInputV2.codeRequired'], { ns: 'share' })}
+ <div className="flex flex-col gap-3 rounded-xl border border-divider-subtle bg-background-section p-3">
+ <div className="flex flex-col gap-1">
+ <label htmlFor="human-input-v2-otp" className="system-sm-semibold text-text-primary">
+ {t(($) => $['humanInputV2.otpLabel'], { ns: 'share' })}
+ </label>
+ <div className="system-xs-regular text-text-secondary">
+ {requesting
+ ? t(($) => $['humanInputV2.requestingCode'], { ns: 'share' })
+ : hasChallenge
+ ? t(($) => $['humanInputV2.codeSent'], { ns: 'share' })
+ : t(($) => $['humanInputV2.codeRequired'], { ns: 'share' })}
+ </div>
</div>
{hasChallenge && (
- <Input
- id="human-input-v2-otp"
- className="mt-3"
- value={otpCode}
- inputMode="numeric"
- autoComplete="one-time-code"
- maxLength={6}
- aria-invalid={Boolean(error)}
- placeholder={t(($) => $['humanInputV2.otpPlaceholder'], { ns: 'share' })}
- onChange={(event) => onOtpChange(event.target.value)}
- />
+ <Field name="otp">
+ <Input
+ id="human-input-v2-otp"
+ value={otpCode}
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ maxLength={6}
+ placeholder={t(($) => $['humanInputV2.otpPlaceholder'], { ns: 'share' })}
+ onChange={(event) => onOtpChange(event.target.value)}
+ />
+ <FieldError />
+ </Field>
)}
{error && (
- <div role="alert" className="mt-2 system-xs-regular text-text-destructive">
+ <div role="alert" className="system-xs-regular text-text-destructive">
{error}
</div>
)}
- <div className="mt-3 flex items-center justify-between gap-3">
+ <div className="flex items-center justify-between gap-3">
{hasChallenge ? (
<>
<div className="system-xs-regular text-text-tertiary">
diff --git a/web/features/new-rag/quality/golden-question-dialog.tsx b/web/features/new-rag/quality/golden-question-dialog.tsx
index 7fdd420281e..e70e72bc47a 100644
--- a/web/features/new-rag/quality/golden-question-dialog.tsx
+++ b/web/features/new-rag/quality/golden-question-dialog.tsx
@@ -198,7 +198,6 @@ function GoldenQuestionDialogSession({
<span className="ms-0.5 text-text-destructive">*</span>
</FieldLabel>
<Textarea
- aria-invalid={questionInvalid}
className="h-22 resize-y"
placeholder={t(($) => $['qualityPage.questionPlaceholder'], { ns: 'knowledgeQuality' })}
value={question}
@@ -208,17 +207,16 @@ function GoldenQuestionDialogSession({
}}
/>
{questionInvalid && (
- <FieldError match className="py-0.5 body-xs-regular text-text-destructive">
+ <FieldError match>
{t(($) => $['qualityPage.questionRequired'], { ns: 'knowledgeQuality' })}
</FieldError>
)}
</Field>
- <Field name="annotation" disabled={pending} invalid={Boolean(error)}>
+ <Field name="annotation" disabled={pending}>
<FieldLabel>
{t(($) => $['qualityPage.annotation'], { ns: 'knowledgeQuality' })}
</FieldLabel>
<Textarea
- aria-invalid={Boolean(error)}
className={mode === 'edit' ? 'h-22 min-h-22 resize-y' : 'h-16 min-h-16 resize-y'}
placeholder={t(($) => $['qualityPage.annotationPlaceholder'], {
ns: 'knowledgeQuality',
@@ -226,7 +224,6 @@ function GoldenQuestionDialogSession({
value={annotation}
onValueChange={setAnnotation}
/>
- {error && <FieldError match>{error}</FieldError>}
</Field>
<div className="grid min-w-0 gap-4">
<Field name="expectedEvidenceIds" disabled={pending}>
@@ -292,7 +289,7 @@ function GoldenQuestionDialogSession({
</div>
)}
</Field>
- <Field name="evidenceSearch" disabled={pending}>
+ <Field name="evidenceSearch" disabled={pending} invalid={Boolean(matchError)}>
<FieldLabel>
{t(($) => $['qualityPage.findEvidence'], { ns: 'knowledgeQuality' })}
</FieldLabel>
@@ -423,6 +420,11 @@ function GoldenQuestionDialogSession({
onValueChange={setTags}
/>
</Field>
+ {error && (
+ <p role="alert" className="system-xs-regular text-text-destructive">
+ {error}
+ </p>
+ )}
<div className="flex justify-end gap-2">
<Button type="button" disabled={pending} onClick={() => onOpenChange(false)}>
{t(($) => $['qualityPage.cancel'], { ns: 'knowledgeQuality' })}
diff --git a/web/features/new-rag/sources/setup/datasource-parameter-form.tsx b/web/features/new-rag/sources/setup/datasource-parameter-form.tsx
index 570afd5b9e2..8ef4cfef0dd 100644
--- a/web/features/new-rag/sources/setup/datasource-parameter-form.tsx
+++ b/web/features/new-rag/sources/setup/datasource-parameter-form.tsx
@@ -65,8 +65,6 @@ function DatasourceParameterField({
const description = showDescription
? localizedDatasourceText(parameter.description, i18n.language, '')
: ''
- const descriptionId = description ? `${generatedId}-description` : undefined
- const errorId = `${generatedId}-error`
const label =
parameter.labelTranslationKey === 'rootUrl'
? t(($) => $.rootUrl, { ns: 'knowledgeSources' })
@@ -94,8 +92,6 @@ function DatasourceParameterField({
? `${label}: ${parameter.min}–${parameter.max}`
: t(($) => $.invalidDatasourceParameter, { ns: 'knowledgeSources', parameter: label })
: undefined
- const describedBy =
- [descriptionId, error ? errorId : undefined].filter(Boolean).join(' ') || undefined
const numberStep = parameter.integer
? 1
: parameter.precision === undefined
@@ -129,28 +125,21 @@ function DatasourceParameterField({
className="mt-0.5"
checked={value === true}
disabled={disabled}
- aria-describedby={describedBy}
onCheckedChange={(checked) => {
setTouched(true)
onChange(checked)
}}
/>
- <span className="min-w-0 flex-1">
- <span className="block system-xs-medium text-text-primary">
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="system-xs-medium text-text-primary">
<ParameterLabel label={label} required={parameter.required} />
</span>
{description && (
- <span id={descriptionId} className="mt-0.5 block body-xs-regular text-text-tertiary">
- {description}
- </span>
+ <span className="body-xs-regular text-text-tertiary">{description}</span>
)}
</span>
</FieldLabel>
- {error && (
- <FieldError id={errorId} match>
- {error}
- </FieldError>
- )}
+ {error && <FieldError match>{error}</FieldError>}
</Field>
)
@@ -167,9 +156,7 @@ function DatasourceParameterField({
<ParameterLabel label={label} required={parameter.required} />
</FieldLabel>
{description && (
- <FieldDescription id={descriptionId} className="mt-0.5 py-0 wrap-break-word">
- {description}
- </FieldDescription>
+ <FieldDescription className="wrap-break-word">{description}</FieldDescription>
)}
</div>
<Switch
@@ -177,18 +164,13 @@ function DatasourceParameterField({
className="mt-0.5"
checked={value === true}
disabled={disabled}
- aria-describedby={describedBy}
onCheckedChange={(checked) => {
setTouched(true)
onChange(checked)
}}
/>
</div>
- {error && (
- <FieldError id={errorId} match>
- {error}
- </FieldError>
- )}
+ {error && <FieldError match>{error}</FieldError>}
</Field>
)
@@ -209,7 +191,7 @@ function DatasourceParameterField({
<SelectLabel>
<ParameterLabel label={label} required={parameter.required} />
</SelectLabel>
- <SelectTrigger aria-describedby={describedBy} size="large">
+ <SelectTrigger size="large">
{parameter.options.find((option) => option.value === selectedValue)
? localizedDatasourceText(
parameter.options.find((option) => option.value === selectedValue)?.label,
@@ -235,12 +217,8 @@ function DatasourceParameterField({
))}
</SelectContent>
</Select>
- {description && <FieldDescription id={descriptionId}>{description}</FieldDescription>}
- {error && (
- <FieldError id={errorId} match>
- {error}
- </FieldError>
- )}
+ {description && <FieldDescription>{description}</FieldDescription>}
+ {error && <FieldError match>{error}</FieldError>}
</Field>
)
}
@@ -251,7 +229,6 @@ function DatasourceParameterField({
<ParameterLabel label={label} required={parameter.required} />
</FieldLabel>
<Input
- aria-describedby={describedBy}
autoComplete="off"
disabled={disabled}
inputMode={
@@ -290,12 +267,8 @@ function DatasourceParameterField({
if (parameter.type === 'number' && numberDraft !== undefined) setNumberDraft(undefined)
}}
/>
- {description && <FieldDescription id={descriptionId}>{description}</FieldDescription>}
- {error && (
- <FieldError id={errorId} match>
- {error}
- </FieldError>
- )}
+ {description && <FieldDescription>{description}</FieldDescription>}
+ {error && <FieldError match>{error}</FieldError>}
</Field>
)
}