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): finish legacy input migration (#42405)

yyh5e9017dbb834
diff --git a/lint.config.ts b/lint.config.ts
index a8aa394ac57..bf84dec886b 100644
--- a/lint.config.ts
+++ b/lint.config.ts
@@ -912,11 +912,6 @@ export const lintConfig = {
message:
'Do not import Floating UI directly in web. Use @langgenius/dify-ui/* primitives instead.',
},
- {
- group: ['**/base/input', '**/base/input/*'],
- message:
- 'Do not import the deprecated web base Input. Use @langgenius/dify-ui/input for standalone inputs, and @langgenius/dify-ui/field for labelled or validated form composition.',
- },
{
group: [
'@/service/base',
@@ -984,11 +979,6 @@ export const lintConfig = {
message:
'Do not import Floating UI directly in web. Use @langgenius/dify-ui/* primitives instead.',
},
- {
- group: ['**/base/input', '**/base/input/*'],
- message:
- 'Do not import the deprecated web base Input. Use @langgenius/dify-ui/input for standalone inputs, and @langgenius/dify-ui/field for labelled or validated form composition.',
- },
{
group: [
'@/service/base',
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index a1d36a661e9..a8e19639158 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -100,14 +100,8 @@
}
},
"web/app/account/(commonLayout)/account-page/email-change-modal.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 3
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 3
- },
"no-restricted-imports": {
- "count": 2
+ "count": 1
}
},
"web/app/components/app/annotation/__tests__/index.spec.tsx": {
@@ -965,11 +959,6 @@
"count": 1
}
},
- "web/app/components/base/emoji-picker/Inner.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/base/error-boundary/index.tsx": {
"eslint-react/jsx-no-key-after-spread": {
"count": 1
@@ -1140,11 +1129,6 @@
"count": 1
}
},
- "web/app/components/base/form/components/base/base-field.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/base/form/components/base/base-form.tsx": {
"typescript/no-explicit-any": {
"count": 6
@@ -1478,17 +1462,6 @@
"count": 2
}
},
- "web/app/components/base/input/index.stories.tsx": {
- "jsx-a11y/label-has-associated-control": {
- "count": 9
- },
- "no-console": {
- "count": 2
- },
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/base/markdown-blocks/__tests__/paragraph.spec.tsx": {
"jsx-a11y/anchor-is-valid": {
"count": 1
@@ -1505,9 +1478,6 @@
}
},
"web/app/components/base/markdown-blocks/form.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"prefer-regex-literals": {
"count": 1
}
@@ -2048,11 +2018,6 @@
"count": 5
}
},
- "web/app/components/datasets/create/step-two/components/inputs.tsx": {
- "no-restricted-imports": {
- "count": 2
- }
- },
"web/app/components/datasets/create/step-two/components/option-card.tsx": {
"jsx-a11y/click-events-have-key-events": {
"count": 1
@@ -3248,11 +3213,6 @@
"count": 2
}
},
- "web/app/components/tools/edit-custom-collection-modal/get-schema.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/tools/edit-custom-collection-modal/index.tsx": {
"eslint-react/set-state-in-effect": {
"count": 4
@@ -3262,15 +3222,6 @@
}
},
"web/app/components/tools/edit-custom-collection-modal/test-api.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 1
- },
- "no-restricted-imports": {
- "count": 1
- },
"typescript/no-explicit-any": {
"count": 1
}
@@ -3293,11 +3244,6 @@
"count": 4
}
},
- "web/app/components/tools/workflow-tool/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/workflow-app/components/__tests__/workflow-children.spec.tsx": {
"eslint-react/static-components": {
"count": 2
@@ -3517,9 +3463,6 @@
"jsx-a11y/no-autofocus": {
"count": 3
},
- "no-restricted-imports": {
- "count": 1
- },
"typescript/no-explicit-any": {
"count": 11
}
@@ -3598,11 +3541,6 @@
"count": 2
}
},
- "web/app/components/workflow/nodes/_base/components/form-input-item.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/_base/components/input-support-select-var.tsx": {
"typescript/no-explicit-any": {
"count": 1
@@ -3875,11 +3813,6 @@
"count": 15
}
},
- "web/app/components/workflow/nodes/assigner/components/var-list/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/assigner/hooks.ts": {
"typescript/no-explicit-any": {
"count": 1
@@ -3972,11 +3905,6 @@
"count": 1
}
},
- "web/app/components/workflow/nodes/http/components/authorization/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/http/components/key-value/key-value-edit/index.tsx": {
"typescript/no-explicit-any": {
"count": 2
@@ -4765,9 +4693,6 @@
"web/app/components/workflow/panel/env-panel/variable-modal.tsx": {
"eslint-react/set-state-in-effect": {
"count": 4
- },
- "no-restricted-imports": {
- "count": 1
}
},
"web/app/components/workflow/panel/global-variable-panel/index.tsx": {
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx
new file mode 100644
index 00000000000..dacc69eaf32
--- /dev/null
+++ b/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx
@@ -0,0 +1,105 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { checkEmailExisted, resetEmail, sendVerifyCode, verifyEmail } from '@/service/common'
+import EmailChangeModal from '../email-change-modal'
+
+vi.mock('@/service/common', () => ({
+ checkEmailExisted: vi.fn(),
+ resetEmail: vi.fn(),
+ sendVerifyCode: vi.fn(),
+ verifyEmail: vi.fn(),
+}))
+
+vi.mock('@/service/use-common', () => ({
+ useLogout: () => ({ mutateAsync: vi.fn() }),
+}))
+
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
+
+describe('EmailChangeModal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(sendVerifyCode).mockResolvedValue({ result: 'success', data: 'email-token' })
+ vi.mocked(verifyEmail).mockResolvedValue({
+ result: 'success',
+ email: '[email protected]',
+ is_valid: true,
+ token: 'verified-token',
+ })
+ vi.mocked(checkEmailExisted).mockResolvedValue({ result: 'success' })
+ })
+
+ it('submits the labeled verification fields with Enter through both email phases', async () => {
+ const user = userEvent.setup()
+ render(<EmailChangeModal email="[email protected]" onClose={vi.fn()} />)
+
+ await user.click(
+ screen.getByRole('button', { name: 'common.account.changeEmail.sendVerifyCode' }),
+ )
+ const originCode = await screen.findByRole('textbox', {
+ name: 'common.account.changeEmail.codeLabel',
+ })
+ await user.type(originCode, '123456{Enter}')
+ expect(verifyEmail).toHaveBeenCalledWith({
+ email: '[email protected]',
+ code: '123456',
+ token: 'email-token',
+ })
+
+ const email = await screen.findByRole('textbox', {
+ name: 'common.account.changeEmail.emailLabel',
+ })
+ await user.type(email, '[email protected]')
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', { name: 'common.account.changeEmail.sendVerifyCode' }),
+ ).toBeEnabled(),
+ )
+ await user.type(email, '{Enter}')
+ expect(sendVerifyCode).toHaveBeenLastCalledWith({
+ email: '[email protected]',
+ phase: 'new_email',
+ token: 'verified-token',
+ })
+
+ const newCode = await screen.findByRole('textbox', {
+ name: 'common.account.changeEmail.codeLabel',
+ })
+ expect(newCode).toHaveValue('')
+ await user.type(newCode, '654321{Enter}')
+ await waitFor(() =>
+ expect(resetEmail).toHaveBeenCalledWith({
+ new_email: '[email protected]',
+ token: 'verified-token',
+ }),
+ )
+ })
+
+ it('associates an unavailable-email error and clears it when the user edits the address', async () => {
+ vi.mocked(checkEmailExisted).mockRejectedValue({
+ status: 400,
+ json: async () => ({ code: 'email_already_in_use' }),
+ })
+ const user = userEvent.setup()
+ render(<EmailChangeModal email="[email protected]" onClose={vi.fn()} />)
+
+ await user.click(
+ screen.getByRole('button', { name: 'common.account.changeEmail.sendVerifyCode' }),
+ )
+ await user.type(
+ await screen.findByRole('textbox', { name: 'common.account.changeEmail.codeLabel' }),
+ '123456{Enter}',
+ )
+ const email = await screen.findByRole('textbox', {
+ name: 'common.account.changeEmail.emailLabel',
+ })
+ await user.type(email, '[email protected]')
+
+ await screen.findByText('common.account.changeEmail.existingEmail')
+ expect(email).toBeInvalid()
+ expect(email).toHaveAccessibleDescription('common.account.changeEmail.existingEmail')
+ await user.clear(email)
+ expect(email).not.toBeInvalid()
+ expect(screen.queryByText('common.account.changeEmail.existingEmail')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx b/web/app/account/(commonLayout)/account-page/email-change-modal.tsx
index 968d76a36e5..391a8d36281 100644
--- a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx
+++ b/web/app/account/(commonLayout)/account-page/email-change-modal.tsx
@@ -1,12 +1,14 @@
import type { ResponseError } from '@/service/fetch'
import { Button } from '@langgenius/dify-ui/button'
-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { IconButton } from '@langgenius/dify-ui/icon-button'
+import { Input } from '@langgenius/dify-ui/input'
import { toast } from '@langgenius/dify-ui/toast'
import { RiCloseLine } from '@remixicon/react'
import { useDebounceFn } from 'ahooks'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
-import Input from '@/app/components/base/input'
import { useRouter } from '@/next/navigation'
import { checkEmailExisted, resetEmail, sendVerifyCode, verifyEmail } from '@/service/common'
import { useLogout } from '@/service/use-common'
@@ -224,201 +226,228 @@ const EmailChangeModal = ({ onClose, email }: Props) => {
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="w-105! p-6!">
- <div className="absolute top-5 right-5 cursor-pointer p-1.5" onClick={onClose}>
- <RiCloseLine className="size-5 text-text-tertiary" />
- </div>
- {step === STEP.start && (
- <>
- <div className="pb-3 title-2xl-semi-bold text-text-primary">
- {t(($) => $['account.changeEmail.title'], { ns: 'common' })}
- </div>
- <div className="space-y-0.5 pt-1 pb-2">
- <div className="body-md-medium text-text-warning">
- {t(($) => $['account.changeEmail.authTip'], { ns: 'common' })}
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (step === STEP.start) void sendCodeToOriginEmail()
+ else if (step === STEP.verifyOrigin) void handleVerifyOriginEmail()
+ else if (step === STEP.newEmail) void sendCodeToNewEmail()
+ else void submitNewEmail()
+ }}
+ >
+ <IconButton
+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}
+ className="absolute top-5 right-5 size-8"
+ onClick={onClose}
+ >
+ <RiCloseLine aria-hidden className="size-5 text-text-tertiary" />
+ </IconButton>
+ {step === STEP.start && (
+ <>
+ <DialogTitle className="pb-3 title-2xl-semi-bold text-text-primary">
+ {t(($) => $['account.changeEmail.title'], { ns: 'common' })}
+ </DialogTitle>
+ <div className="space-y-0.5 pt-1 pb-2">
+ <div className="body-md-medium text-text-warning">
+ {t(($) => $['account.changeEmail.authTip'], { ns: 'common' })}
+ </div>
+ <div className="body-md-regular text-text-secondary">
+ <Trans
+ i18nKey={($) => $['account.changeEmail.content1']}
+ ns="common"
+ components={{
+ email: <span className="body-md-medium text-text-primary"></span>,
+ }}
+ values={{ email }}
+ />
+ </div>
</div>
- <div className="body-md-regular text-text-secondary">
- <Trans
- i18nKey={($) => $['account.changeEmail.content1']}
- ns="common"
- components={{ email: <span className="body-md-medium text-text-primary"></span> }}
- values={{ email }}
- />
+ <div className="pt-3"></div>
+ <div className="space-y-2">
+ <Button className="w-full!" variant="primary" type="submit">
+ {t(($) => $['account.changeEmail.sendVerifyCode'], { ns: 'common' })}
+ </Button>
+ <Button className="w-full!" onClick={onClose}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
</div>
- </div>
- <div className="pt-3"></div>
- <div className="space-y-2">
- <Button className="w-full!" variant="primary" onClick={sendCodeToOriginEmail}>
- {t(($) => $['account.changeEmail.sendVerifyCode'], { ns: 'common' })}
- </Button>
- <Button className="w-full!" onClick={onClose}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- </div>
- </>
- )}
- {step === STEP.verifyOrigin && (
- <>
- <div className="pb-3 title-2xl-semi-bold text-text-primary">
- {t(($) => $['account.changeEmail.verifyEmail'], { ns: 'common' })}
- </div>
- <div className="space-y-0.5 pt-1 pb-2">
- <div className="body-md-regular text-text-secondary">
- <Trans
- i18nKey={($) => $['account.changeEmail.content2']}
- ns="common"
- components={{ email: <span className="body-md-medium text-text-primary"></span> }}
- values={{ email }}
- />
- </div>
- </div>
- <div className="pt-3">
- <div className="mb-1 flex h-6 items-center system-sm-medium text-text-secondary">
- {t(($) => $['account.changeEmail.codeLabel'], { ns: 'common' })}
+ </>
+ )}
+ {step === STEP.verifyOrigin && (
+ <>
+ <DialogTitle className="pb-3 title-2xl-semi-bold text-text-primary">
+ {t(($) => $['account.changeEmail.verifyEmail'], { ns: 'common' })}
+ </DialogTitle>
+ <div className="space-y-0.5 pt-1 pb-2">
+ <div className="body-md-regular text-text-secondary">
+ <Trans
+ i18nKey={($) => $['account.changeEmail.content2']}
+ ns="common"
+ components={{
+ email: <span className="body-md-medium text-text-primary"></span>,
+ }}
+ values={{ email }}
+ />
+ </div>
</div>
- <Input
- className="w-full!"
- placeholder={t(($) => $['account.changeEmail.codePlaceholder'], { ns: 'common' })}
- value={code}
- onChange={(e) => setCode(e.target.value)}
- maxLength={6}
- />
- </div>
- <div className="mt-3 space-y-2">
- <Button
- disabled={code.length !== 6}
- className="w-full!"
- variant="primary"
- onClick={handleVerifyOriginEmail}
- >
- {t(($) => $['account.changeEmail.continue'], { ns: 'common' })}
- </Button>
- <Button className="w-full!" onClick={onClose}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- </div>
- <div className="mt-3 flex items-center gap-1 system-xs-regular text-text-tertiary">
- <span>{t(($) => $['account.changeEmail.resendTip'], { ns: 'common' })}</span>
- {time > 0 && (
- <span>
- {t(($) => $['account.changeEmail.resendCount'], { ns: 'common', count: time })}
- </span>
- )}
- {!time && (
- <span
- onClick={sendCodeToOriginEmail}
- className="cursor-pointer system-xs-medium text-text-accent-secondary"
+ <Field name="code" className="pt-3">
+ <FieldLabel>
+ {t(($) => $['account.changeEmail.codeLabel'], { ns: 'common' })}
+ </FieldLabel>
+ <Input
+ className="w-full!"
+ placeholder={t(($) => $['account.changeEmail.codePlaceholder'], { ns: 'common' })}
+ value={code}
+ onValueChange={(value) => setCode(value)}
+ autoComplete="one-time-code"
+ maxLength={6}
+ />
+ </Field>
+ <div className="mt-3 space-y-2">
+ <Button
+ disabled={code.length !== 6}
+ className="w-full!"
+ variant="primary"
+ type="submit"
>
- {t(($) => $['account.changeEmail.resend'], { ns: 'common' })}
- </span>
- )}
- </div>
- </>
- )}
- {step === STEP.newEmail && (
- <>
- <div className="pb-3 title-2xl-semi-bold text-text-primary">
- {t(($) => $['account.changeEmail.newEmail'], { ns: 'common' })}
- </div>
- <div className="space-y-0.5 pt-1 pb-2">
- <div className="body-md-regular text-text-secondary">
- {t(($) => $['account.changeEmail.content3'], { ns: 'common' })}
+ {t(($) => $['account.changeEmail.continue'], { ns: 'common' })}
+ </Button>
+ <Button className="w-full!" onClick={onClose}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
</div>
- </div>
- <div className="pt-3">
- <div className="mb-1 flex h-6 items-center system-sm-medium text-text-secondary">
- {t(($) => $['account.changeEmail.emailLabel'], { ns: 'common' })}
+ <div className="mt-3 flex items-center gap-1 system-xs-regular text-text-tertiary">
+ <span>{t(($) => $['account.changeEmail.resendTip'], { ns: 'common' })}</span>
+ {time > 0 && (
+ <span>
+ {t(($) => $['account.changeEmail.resendCount'], { ns: 'common', count: time })}
+ </span>
+ )}
+ {!time && (
+ <button
+ type="button"
+ onClick={sendCodeToOriginEmail}
+ className="cursor-pointer rounded-sm system-xs-medium text-text-accent-secondary outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"
+ >
+ {t(($) => $['account.changeEmail.resend'], { ns: 'common' })}
+ </button>
+ )}
</div>
- <Input
- className="w-full!"
- placeholder={t(($) => $['account.changeEmail.emailPlaceholder'], { ns: 'common' })}
- value={mail}
- onChange={(e) => handleNewEmailValueChange(e.target.value)}
- destructive={newEmailExited || unAvailableEmail}
- />
- {newEmailExited && (
- <div className="mt-1 py-0.5 body-xs-regular text-text-destructive">
- {t(($) => $['account.changeEmail.existingEmail'], { ns: 'common' })}
+ </>
+ )}
+ {step === STEP.newEmail && (
+ <>
+ <DialogTitle className="pb-3 title-2xl-semi-bold text-text-primary">
+ {t(($) => $['account.changeEmail.newEmail'], { ns: 'common' })}
+ </DialogTitle>
+ <div className="space-y-0.5 pt-1 pb-2">
+ <div className="body-md-regular text-text-secondary">
+ {t(($) => $['account.changeEmail.content3'], { ns: 'common' })}
</div>
- )}
- {unAvailableEmail && (
- <div className="mt-1 py-0.5 body-xs-regular text-text-destructive">
- {t(($) => $['account.changeEmail.unAvailableEmail'], { ns: 'common' })}
- </div>
- )}
- </div>
- <div className="mt-3 space-y-2">
- <Button
- disabled={isSendCodeDisabled}
- className="w-full!"
- variant="primary"
- onClick={sendCodeToNewEmail}
- >
- {t(($) => $['account.changeEmail.sendVerifyCode'], { ns: 'common' })}
- </Button>
- <Button className="w-full!" onClick={onClose}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- </div>
- </>
- )}
- {step === STEP.verifyNew && (
- <>
- <div className="pb-3 title-2xl-semi-bold text-text-primary">
- {t(($) => $['account.changeEmail.verifyNew'], { ns: 'common' })}
- </div>
- <div className="space-y-0.5 pt-1 pb-2">
- <div className="body-md-regular text-text-secondary">
- <Trans
- i18nKey={($) => $['account.changeEmail.content4']}
- ns="common"
- components={{ email: <span className="body-md-medium text-text-primary"></span> }}
- values={{ email: mail }}
+ </div>
+ <Field name="email" invalid={newEmailExited || unAvailableEmail} className="pt-3">
+ <FieldLabel>
+ {t(($) => $['account.changeEmail.emailLabel'], { ns: 'common' })}
+ </FieldLabel>
+ <Input
+ className="w-full!"
+ placeholder={t(($) => $['account.changeEmail.emailPlaceholder'], {
+ ns: 'common',
+ })}
+ value={mail}
+ onValueChange={(value) => handleNewEmailValueChange(value)}
+ type="email"
+ autoComplete="email"
/>
+ {newEmailExited && (
+ <FieldError match>
+ {t(($) => $['account.changeEmail.existingEmail'], { ns: 'common' })}
+ </FieldError>
+ )}
+ {unAvailableEmail && (
+ <FieldError match>
+ {t(($) => $['account.changeEmail.unAvailableEmail'], { ns: 'common' })}
+ </FieldError>
+ )}
+ </Field>
+ <div className="mt-3 space-y-2">
+ <Button
+ disabled={isSendCodeDisabled}
+ className="w-full!"
+ variant="primary"
+ type="submit"
+ >
+ {t(($) => $['account.changeEmail.sendVerifyCode'], { ns: 'common' })}
+ </Button>
+ <Button className="w-full!" onClick={onClose}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
</div>
- </div>
- <div className="pt-3">
- <div className="mb-1 flex h-6 items-center system-sm-medium text-text-secondary">
- {t(($) => $['account.changeEmail.codeLabel'], { ns: 'common' })}
+ </>
+ )}
+ {step === STEP.verifyNew && (
+ <>
+ <DialogTitle className="pb-3 title-2xl-semi-bold text-text-primary">
+ {t(($) => $['account.changeEmail.verifyNew'], { ns: 'common' })}
+ </DialogTitle>
+ <div className="space-y-0.5 pt-1 pb-2">
+ <div className="body-md-regular text-text-secondary">
+ <Trans
+ i18nKey={($) => $['account.changeEmail.content4']}
+ ns="common"
+ components={{
+ email: <span className="body-md-medium text-text-primary"></span>,
+ }}
+ values={{ email: mail }}
+ />
+ </div>
</div>
- <Input
- className="w-full!"
- placeholder={t(($) => $['account.changeEmail.codePlaceholder'], { ns: 'common' })}
- value={code}
- onChange={(e) => setCode(e.target.value)}
- maxLength={6}
- />
- </div>
- <div className="mt-3 space-y-2">
- <Button
- disabled={code.length !== 6}
- className="w-full!"
- variant="primary"
- onClick={submitNewEmail}
- >
- {t(($) => $['account.changeEmail.changeTo'], { ns: 'common', email: mail })}
- </Button>
- <Button className="w-full!" onClick={onClose}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- </div>
- <div className="mt-3 flex items-center gap-1 system-xs-regular text-text-tertiary">
- <span>{t(($) => $['account.changeEmail.resendTip'], { ns: 'common' })}</span>
- {time > 0 && (
- <span>
- {t(($) => $['account.changeEmail.resendCount'], { ns: 'common', count: time })}
- </span>
- )}
- {!time && (
- <span
- onClick={sendCodeToNewEmail}
- className="cursor-pointer system-xs-medium text-text-accent-secondary"
+ <Field name="code" className="pt-3">
+ <FieldLabel>
+ {t(($) => $['account.changeEmail.codeLabel'], { ns: 'common' })}
+ </FieldLabel>
+ <Input
+ className="w-full!"
+ placeholder={t(($) => $['account.changeEmail.codePlaceholder'], { ns: 'common' })}
+ value={code}
+ onValueChange={(value) => setCode(value)}
+ autoComplete="one-time-code"
+ maxLength={6}
+ />
+ </Field>
+ <div className="mt-3 space-y-2">
+ <Button
+ disabled={code.length !== 6}
+ className="w-full!"
+ variant="primary"
+ type="submit"
>
- {t(($) => $['account.changeEmail.resend'], { ns: 'common' })}
- </span>
- )}
- </div>
- </>
- )}
+ {t(($) => $['account.changeEmail.changeTo'], { ns: 'common', email: mail })}
+ </Button>
+ <Button className="w-full!" onClick={onClose}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
+ </div>
+ <div className="mt-3 flex items-center gap-1 system-xs-regular text-text-tertiary">
+ <span>{t(($) => $['account.changeEmail.resendTip'], { ns: 'common' })}</span>
+ {time > 0 && (
+ <span>
+ {t(($) => $['account.changeEmail.resendCount'], { ns: 'common', count: time })}
+ </span>
+ )}
+ {!time && (
+ <button
+ type="button"
+ onClick={sendCodeToNewEmail}
+ className="cursor-pointer rounded-sm system-xs-medium text-text-accent-secondary outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"
+ >
+ {t(($) => $['account.changeEmail.resend'], { ns: 'common' })}
+ </button>
+ )}
+ </div>
+ </>
+ )}
+ </form>
</DialogContent>
</Dialog>
)
diff --git a/web/app/components/base/emoji-picker/Inner.tsx b/web/app/components/base/emoji-picker/Inner.tsx
index f30319045e7..c23c93ded0f 100644
--- a/web/app/components/base/emoji-picker/Inner.tsx
+++ b/web/app/components/base/emoji-picker/Inner.tsx
@@ -1,14 +1,14 @@
'use client'
import type { EmojiMartData } from '@emoji-mart/data'
-import type { ChangeEvent } from 'react'
import data from '@emoji-mart/data'
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline'
import { cn } from '@langgenius/dify-ui/cn'
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import { init } from 'emoji-mart'
import * as React from 'react'
import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
import Divider from '@/app/components/base/divider'
-import Input from '@/app/components/base/input'
import { searchEmoji } from '@/utils/emoji'
import { backgroundColors, defaultEmojiBackground } from './constants'
@@ -22,6 +22,7 @@ type IEmojiPickerInnerProps = {
}
function EmojiPickerInner({ emoji, background, onSelect, className }: IEmojiPickerInnerProps) {
+ const { t } = useTranslation()
const { categories } = data as EmojiMartData
const [selectedEmoji, setSelectedEmoji] = useState(emoji || '')
const [selectedBackground, setSelectedBackground] = useState(background || defaultEmojiBackground)
@@ -45,26 +46,25 @@ function EmojiPickerInner({ emoji, background, onSelect, className }: IEmojiPick
return (
<div className={cn(className, 'flex flex-col')}>
<div className="flex w-full flex-col items-center px-3 pb-2">
- <div className="relative w-full">
- <div className="pointer-events-none absolute inset-y-0 left-0 z-10 flex items-center pl-3">
- <MagnifyingGlassIcon className="size-5 text-text-quaternary" aria-hidden="true" />
- </div>
- <Input
- className="pl-10"
+ <InputGroup>
+ <InputGroupInput
type="search"
- id="search"
+ aria-label={t(($) => $['operation.search'], { ns: 'common' })}
placeholder="Search emojis..."
- onChange={async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.value === '') {
+ onValueChange={async (value) => {
+ if (value === '') {
setIsSearching(false)
} else {
setIsSearching(true)
- const emojis = await searchEmoji(e.target.value)
+ const emojis = await searchEmoji(value)
setSearchedEmojis(emojis)
}
}}
/>
- </div>
+ <InputGroupAddon className="ps-3 pe-2">
+ <MagnifyingGlassIcon className="size-5 text-text-quaternary" aria-hidden="true" />
+ </InputGroupAddon>
+ </InputGroup>
</div>
<Divider className="my-3" />
diff --git a/web/app/components/base/form/__tests__/index.spec.tsx b/web/app/components/base/form/__tests__/index.spec.tsx
index 11283fdb979..57c3a9d747c 100644
--- a/web/app/components/base/form/__tests__/index.spec.tsx
+++ b/web/app/components/base/form/__tests__/index.spec.tsx
@@ -1,4 +1,5 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { useAppForm, withForm } from '../index'
const FormHarness = ({ onSubmit }: { onSubmit: (value: Record<string, unknown>) => void }) => {
@@ -8,12 +9,15 @@ const FormHarness = ({ onSubmit }: { onSubmit: (value: Record<string, unknown>)
})
return (
- <form>
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ void form.handleSubmit()
+ }}
+ >
<form.AppField name="title" children={(field) => <field.TextField label="Title" />} />
<form.AppForm>
- <button type="button" onClick={() => form.handleSubmit()}>
- Submit
- </button>
+ <button type="submit">Submit</button>
</form.AppForm>
</form>
)
@@ -40,12 +44,16 @@ const WithFormHarness = () => {
describe('form index exports', () => {
it('should submit values through the generated app form', async () => {
const onSubmit = vi.fn()
+ const user = userEvent.setup()
render(<FormHarness onSubmit={onSubmit} />)
- fireEvent.click(screen.getByRole('button', { name: /submit/i }))
+ const input = screen.getByRole('textbox', { name: 'Title' })
+ await user.clear(input)
+ await user.type(input, 'Updated title')
+ await user.click(screen.getByRole('button', { name: /submit/i }))
await waitFor(() => {
- expect(onSubmit).toHaveBeenCalledWith({ title: 'Initial title' })
+ expect(onSubmit).toHaveBeenCalledWith({ title: 'Updated title' })
})
})
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 169fb6f6d56..d448a797b65 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
@@ -344,7 +344,9 @@ describe('BaseField', () => {
expect(screen.getByDisplayValue('abc')).toHaveAttribute('type', 'password')
})
- it('should render number input with number type', () => {
+ it('keeps numeric edits, zero and an empty value distinct at the form boundary', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
renderBaseField({
formSchema: {
type: FormTypeEnum.textNumber,
@@ -353,9 +355,22 @@ describe('BaseField', () => {
required: false,
},
defaultValues: { count: 7 },
+ onChange,
})
- expect(screen.getByDisplayValue('7')).toHaveAttribute('type', 'number')
+ const input = screen.getByRole('textbox', { name: 'Count' })
+ expect(input).toHaveValue('7')
+ await user.clear(input)
+ await user.type(input, '3.5')
+ await user.tab()
+ expect(onChange).toHaveBeenLastCalledWith('count', 3.5)
+ await user.clear(input)
+ await user.type(input, '0')
+ await user.tab()
+ expect(onChange).toHaveBeenLastCalledWith('count', 0)
+ await user.clear(input)
+ await user.tab()
+ expect(onChange).toHaveBeenLastCalledWith('count', null)
})
it('should render translated object label content', () => {
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 231053e78db..7e7c2383d90 100644
--- a/web/app/components/base/form/components/base/base-field.tsx
+++ b/web/app/components/base/form/components/base/base-field.tsx
@@ -3,6 +3,9 @@ import type { FieldState, FormSchema, TypeWithI18N } from '@/app/components/base
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 { Input } from '@langgenius/dify-ui/input'
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
+import { NumberField, NumberFieldGroup, NumberFieldInput } from '@langgenius/dify-ui/number-field'
import { Radio, RadioGroup } from '@langgenius/dify-ui/radio-group'
import {
Select,
@@ -18,9 +21,9 @@ import { useStore } from '@tanstack/react-form'
import { isValidElement, memo, useCallback, useId, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { CheckboxList } from '@/app/components/base/checkbox-list'
+import { CopyFeedback } from '@/app/components/base/copy-feedback'
import { FormItemValidateStatusEnum, FormTypeEnum } from '@/app/components/base/form/types'
import { Infotip } from '@/app/components/base/infotip'
-import Input from '@/app/components/base/input'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import { useTriggerPluginDynamicOptions } from '@/service/use-triggers'
@@ -28,8 +31,6 @@ const getExtraProps = (type: FormTypeEnum) => {
switch (type) {
case FormTypeEnum.secretInput:
return { type: 'password', autoComplete: 'new-password' }
- case FormTypeEnum.textNumber:
- return { type: 'number' }
default:
return { type: 'text' }
}
@@ -85,7 +86,7 @@ const VALIDATE_STATUS_STYLE_MAP: Record<
},
[FormItemValidateStatusEnum.Warning]: {
componentClassName:
- 'border-components-input-border-warning focus:border-components-input-border-warning',
+ 'border-components-input-border-warning focus:border-components-input-border-warning has-[input:focus]:border-components-input-border-warning',
textClassName: 'text-text-warning',
infoFieldName: 'warnings',
},
@@ -273,6 +274,17 @@ const BaseField = ({
const selectPlaceholder = isDynamicSelect ? dynamicPlaceholder : translatedPlaceholder
const handleSelectChange = isDynamicSelect ? field.handleChange : handleChange
const selectDisabled = disabled || (isDynamicSelect && isDynamicOptionsLoading)
+ const textInputProps = {
+ id: controlId,
+ name: field.name,
+ ...controlProps,
+ value: stringValue ?? '',
+ onValueChange: handleChange,
+ onBlur: field.handleBlur,
+ disabled,
+ placeholder: translatedPlaceholder,
+ ...getExtraProps(formItemType),
+ }
const content = (
<>
@@ -301,28 +313,74 @@ const BaseField = ({
)}
</div>
<div className={cn(inputContainerClassName)} data-form-field={field.name}>
- {[FormTypeEnum.textInput, FormTypeEnum.secretInput, FormTypeEnum.textNumber].includes(
- formItemType,
- ) && (
- <Input
- id={controlId}
- name={field.name}
- {...controlProps}
- className={cn(
- inputClassName,
- VALIDATE_STATUS_STYLE_MAP[validateStatus as FormItemValidateStatusEnum]
- ?.componentClassName,
+ {[FormTypeEnum.textInput, FormTypeEnum.secretInput].includes(formItemType) && (
+ <Field
+ className="contents"
+ invalid={validateStatus === FormItemValidateStatusEnum.Error}
+ >
+ {showCopy ? (
+ <InputGroup
+ className={cn(
+ inputClassName,
+ VALIDATE_STATUS_STYLE_MAP[validateStatus as FormItemValidateStatusEnum]
+ ?.componentClassName,
+ )}
+ >
+ <InputGroupInput {...textInputProps} />
+ <InputGroupAddon align="inline-end" className="pe-0">
+ <CopyFeedback
+ content={stringValue ?? ''}
+ className="size-7 hover:bg-transparent"
+ />
+ </InputGroupAddon>
+ </InputGroup>
+ ) : (
+ <Input
+ {...textInputProps}
+ className={cn(
+ inputClassName,
+ VALIDATE_STATUS_STYLE_MAP[validateStatus as FormItemValidateStatusEnum]
+ ?.componentClassName,
+ )}
+ />
)}
- value={value || ''}
- onChange={(e) => {
- handleChange(e.target.value)
- }}
- onBlur={field.handleBlur}
- disabled={disabled}
- placeholder={translatedPlaceholder}
- {...getExtraProps(formItemType)}
- showCopyIcon={showCopy}
- />
+ </Field>
+ )}
+ {formItemType === FormTypeEnum.textNumber && (
+ <Field
+ className="contents"
+ invalid={validateStatus === FormItemValidateStatusEnum.Error}
+ >
+ <NumberField
+ name={field.name}
+ step="any"
+ value={value == null || value === '' ? null : Number(value)}
+ disabled={disabled}
+ onValueChange={(value) => handleChange(value)}
+ >
+ <NumberFieldGroup
+ className={cn(
+ inputClassName,
+ validateStatus === FormItemValidateStatusEnum.Warning &&
+ VALIDATE_STATUS_STYLE_MAP[FormItemValidateStatusEnum.Warning]
+ .componentClassName,
+ )}
+ >
+ <NumberFieldInput
+ id={controlId}
+ {...controlProps}
+ onBlur={field.handleBlur}
+ placeholder={translatedPlaceholder}
+ />
+ {showCopy && (
+ <CopyFeedback
+ content={value == null ? '' : String(value)}
+ className="size-7 shrink-0 hover:bg-transparent"
+ />
+ )}
+ </NumberFieldGroup>
+ </NumberField>
+ </Field>
)}
{isSelect && (
<>
diff --git a/web/app/components/base/form/components/field/__tests__/text.spec.tsx b/web/app/components/base/form/components/field/__tests__/text.spec.tsx
deleted file mode 100644
index 5ebc82e8586..00000000000
--- a/web/app/components/base/form/components/field/__tests__/text.spec.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import TextField from '../text'
-
-const mockField = {
- name: 'text-field',
- state: {
- value: 'Initial text',
- },
- handleChange: vi.fn(),
- handleBlur: vi.fn(),
-}
-
-vi.mock('../../..', () => ({
- useFieldContext: () => mockField,
-}))
-
-describe('TextField', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockField.state.value = 'Initial text'
- })
-
- it('should render current value', () => {
- render(<TextField label="Name" />)
- expect(screen.getByLabelText('Name')).toHaveValue('Initial text')
- })
-
- it('should update value when users type', () => {
- render(<TextField label="Name" />)
- fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Updated text' } })
- expect(mockField.handleChange).toHaveBeenCalledWith('Updated text')
- })
-})
diff --git a/web/app/components/base/form/components/field/text.tsx b/web/app/components/base/form/components/field/text.tsx
index 28a4919cee6..6ec2592cb88 100644
--- a/web/app/components/base/form/components/field/text.tsx
+++ b/web/app/components/base/form/components/field/text.tsx
@@ -1,16 +1,19 @@
-import type { InputProps } from '../../../input'
+import type { InputProps } from '@langgenius/dify-ui/input'
import type { LabelProps } from '../label'
import { cn } from '@langgenius/dify-ui/cn'
+import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'
import { useFieldContext } from '../..'
-import Input from '../../../input'
import Label from '../label'
type TextFieldProps = {
label: string
labelOptions?: Omit<LabelProps, 'htmlFor' | 'label'>
className?: string
-} & Omit<InputProps, 'className' | 'onChange' | 'onBlur' | 'value' | 'id'>
+} & Omit<
+ InputProps,
+ 'className' | 'onChange' | 'onValueChange' | 'onBlur' | 'value' | 'defaultValue' | 'id' | 'name'
+>
const TextField = ({ label, labelOptions, className, ...inputProps }: TextFieldProps) => {
const field = useFieldContext<string>()
@@ -20,8 +23,9 @@ const TextField = ({ label, labelOptions, className, ...inputProps }: TextFieldP
<Label htmlFor={field.name} label={label} {...(labelOptions ?? {})} />
<Input
id={field.name}
+ name={field.name}
value={field.state.value}
- onChange={(e) => field.handleChange(e.target.value)}
+ onValueChange={(value) => field.handleChange(value)}
onBlur={field.handleBlur}
{...inputProps}
/>
diff --git a/web/app/components/base/form/hooks/__tests__/use-get-validators.spec.ts b/web/app/components/base/form/hooks/__tests__/use-get-validators.spec.ts
index c997011ce8e..3300fbbfdb8 100644
--- a/web/app/components/base/form/hooks/__tests__/use-get-validators.spec.ts
+++ b/web/app/components/base/form/hooks/__tests__/use-get-validators.spec.ts
@@ -8,6 +8,21 @@ vi.mock('@/hooks/use-i18n', () => ({
}))
describe('useGetValidators', () => {
+ it('accepts numeric zero but rejects a cleared required number field', () => {
+ const { result } = renderHook(() => useGetValidators())
+ const validators = result.current.getValidators({
+ name: 'amount',
+ label: 'Amount',
+ required: true,
+ type: FormTypeEnum.textNumber,
+ })
+
+ for (const validate of [validators?.onMount, validators?.onChange, validators?.onBlur]) {
+ expect(validate?.({ value: 0 })).toBeUndefined()
+ expect(validate?.({ value: null })).toContain('common.errorMsg.fieldRequired')
+ }
+ })
+
it('should create required validators when field is required without custom validators', () => {
const { result } = renderHook(() => useGetValidators())
const validators = result.current.getValidators({
diff --git a/web/app/components/base/form/hooks/use-get-validators.ts b/web/app/components/base/form/hooks/use-get-validators.ts
index 3d1fa230546..0145dc50e30 100644
--- a/web/app/components/base/form/hooks/use-get-validators.ts
+++ b/web/app/components/base/form/hooks/use-get-validators.ts
@@ -23,21 +23,21 @@ export const useGetValidators = () => {
if (required && !validators) {
mergedValidators = {
onMount: ({ value }: any) => {
- if (!value)
+ if (!value && value !== 0)
return t(($) => $['errorMsg.fieldRequired'], {
ns: 'common',
field: memorizedLabel || name,
})
},
onChange: ({ value }: any) => {
- if (!value)
+ if (!value && value !== 0)
return t(($) => $['errorMsg.fieldRequired'], {
ns: 'common',
field: memorizedLabel || name,
})
},
onBlur: ({ value }: any) => {
- if (!value)
+ if (!value && value !== 0)
return t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: memorizedLabel })
},
}
diff --git a/web/app/components/base/input-with-copy/__tests__/index.spec.tsx b/web/app/components/base/input-with-copy/__tests__/index.spec.tsx
deleted file mode 100644
index e87d309e98a..00000000000
--- a/web/app/components/base/input-with-copy/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,222 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import InputWithCopy from '../index'
-
-// Create a controllable mock for useClipboard
-const mockCopy = vi.fn()
-let mockCopied = false
-const mockReset = vi.fn()
-
-vi.mock('foxact/use-clipboard', () => ({
- useClipboard: () => ({
- copy: mockCopy,
- copied: mockCopied,
- reset: mockReset,
- }),
-}))
-
-describe('InputWithCopy component', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockCopy.mockClear()
- mockReset.mockClear()
- mockCopied = false
- })
-
- it('renders correctly with default props', () => {
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="test value" onChange={mockOnChange} />)
- const input = screen.getByDisplayValue('test value')
- const copyButton = screen.getByRole('button')
- expect(input).toBeInTheDocument()
- expect(copyButton).toBeInTheDocument()
- })
-
- it('hides copy button when showCopyButton is false', () => {
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="test value" onChange={mockOnChange} showCopyButton={false} />)
- const input = screen.getByDisplayValue('test value')
- const copyButton = screen.queryByRole('button')
- expect(input).toBeInTheDocument()
- expect(copyButton).not.toBeInTheDocument()
- })
-
- it('calls copy function with input value when copy button is clicked', () => {
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="test value" onChange={mockOnChange} />)
-
- const copyButton = screen.getByRole('button')
- fireEvent.click(copyButton)
-
- expect(mockCopy).toHaveBeenCalledWith('test value')
- })
-
- it('calls copy function with custom value when copyValue prop is provided', () => {
- const mockOnChange = vi.fn()
- render(
- <InputWithCopy value="display value" onChange={mockOnChange} copyValue="custom copy value" />,
- )
-
- const copyButton = screen.getByRole('button')
- fireEvent.click(copyButton)
-
- expect(mockCopy).toHaveBeenCalledWith('custom copy value')
- })
-
- it('calls onCopy callback when copy button is clicked', () => {
- const onCopyMock = vi.fn()
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="test value" onChange={mockOnChange} onCopy={onCopyMock} />)
-
- const copyButton = screen.getByRole('button')
- fireEvent.click(copyButton)
-
- expect(onCopyMock).toHaveBeenCalledWith('test value')
- })
-
- it('shows copied state when copied is true', () => {
- mockCopied = true
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="test value" onChange={mockOnChange} />)
-
- const copyButton = screen.getByRole('button')
- // Hover over the button to trigger tooltip
- fireEvent.mouseEnter(copyButton)
-
- // The icon should change to filled version when copied
- // We verify the component renders without error in copied state
- expect(copyButton).toBeInTheDocument()
- })
-
- it('passes through all input props correctly', () => {
- const mockOnChange = vi.fn()
- render(
- <InputWithCopy
- value="test value"
- onChange={mockOnChange}
- placeholder="Custom placeholder"
- disabled
- readOnly
- className="custom-class"
- />,
- )
-
- const input = screen.getByDisplayValue('test value')
- expect(input).toHaveAttribute('placeholder', 'Custom placeholder')
- expect(input).toBeDisabled()
- expect(input).toHaveAttribute('readonly')
- expect(input).toHaveClass('custom-class')
- })
-
- it('handles empty value correctly', () => {
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="" onChange={mockOnChange} />)
- const input = screen.getByRole('textbox')
- const copyButton = screen.getByRole('button')
-
- expect(input).toBeInTheDocument()
- expect(input).toHaveValue('')
- expect(copyButton).toBeInTheDocument()
-
- // Clicking copy button with empty value should call copy with empty string
- fireEvent.click(copyButton)
- expect(mockCopy).toHaveBeenCalledWith('')
- })
-
- it('maintains focus on input after copy', () => {
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="test value" onChange={mockOnChange} />)
-
- const input = screen.getByDisplayValue('test value')
- const copyButton = screen.getByRole('button')
-
- input.focus()
- expect(input).toHaveFocus()
-
- fireEvent.click(copyButton)
-
- // Input should maintain focus after copy
- expect(input).toHaveFocus()
- })
-
- it('converts non-string value to string for copying', () => {
- const mockOnChange = vi.fn()
- // number value triggers String(value || '') branch where typeof value !== 'string'
- render(<InputWithCopy value={12345} onChange={mockOnChange} />)
-
- const copyButton = screen.getByRole('button')
- fireEvent.click(copyButton)
-
- expect(mockCopy).toHaveBeenCalledWith('12345')
- })
-
- it('handles undefined value by converting to empty string', () => {
- const mockOnChange = vi.fn()
- // undefined value triggers String(value || '') where value is falsy
- render(<InputWithCopy value={undefined} onChange={mockOnChange} />)
-
- const copyButton = screen.getByRole('button')
- fireEvent.click(copyButton)
-
- expect(mockCopy).toHaveBeenCalledWith('')
- })
-
- it('shows copied tooltip text when copied state is true', () => {
- mockCopied = true
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="test value" onChange={mockOnChange} />)
-
- const copyButton = screen.getByRole('button', {
- name: 'appOverview.overview.appInfo.embedded.copied',
- })
- expect(copyButton).toBeInTheDocument()
- })
-
- it('shows copy tooltip text when copied state is false', () => {
- mockCopied = false
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="test value" onChange={mockOnChange} />)
-
- const copyButton = screen.getByRole('button', {
- name: 'appOverview.overview.appInfo.embedded.copy',
- })
- expect(copyButton).toBeInTheDocument()
- })
-
- it('calls reset on mouse leave from copy button wrapper', () => {
- const mockOnChange = vi.fn()
- render(<InputWithCopy value="test value" onChange={mockOnChange} />)
-
- const copyButton = screen.getByRole('button')
- fireEvent.mouseLeave(copyButton)
-
- expect(mockReset).toHaveBeenCalled()
- })
-
- it('copies copyValue over non-string input value when both provided', () => {
- const mockOnChange = vi.fn()
- render(<InputWithCopy value={42} onChange={mockOnChange} copyValue="override-copy" />)
-
- const copyButton = screen.getByRole('button')
- fireEvent.click(copyButton)
-
- expect(mockCopy).toHaveBeenCalledWith('override-copy')
- })
-
- it('invokes onCopy with copyValue when copyValue is provided', () => {
- const onCopyMock = vi.fn()
- const mockOnChange = vi.fn()
- render(
- <InputWithCopy
- value="display"
- onChange={mockOnChange}
- copyValue="custom"
- onCopy={onCopyMock}
- />,
- )
-
- const copyButton = screen.getByRole('button')
- fireEvent.click(copyButton)
-
- expect(onCopyMock).toHaveBeenCalledWith('custom')
- })
-})
diff --git a/web/app/components/base/input-with-copy/index.tsx b/web/app/components/base/input-with-copy/index.tsx
deleted file mode 100644
index e35ed323ccd..00000000000
--- a/web/app/components/base/input-with-copy/index.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-'use client'
-import type { InputProps } from '../input'
-import { cn } from '@langgenius/dify-ui/cn'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
-import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { useClipboard } from 'foxact/use-clipboard'
-import * as React from 'react'
-import { useTranslation } from 'react-i18next'
-
-type InputWithCopyProps = {
- showCopyButton?: boolean
- copyValue?: string // Value to copy, defaults to input value
- onCopy?: (value: string) => void // Callback when copy is triggered
-} & Omit<InputProps, 'showClearIcon' | 'onCopy'> // Remove conflicting props
-
-const prefixEmbedded = 'overview.appInfo.embedded'
-
-const InputWithCopy = React.forwardRef<HTMLInputElement, InputWithCopyProps>(
- ({ showCopyButton = true, copyValue, onCopy, value, wrapperClassName, ...inputProps }, ref) => {
- const { t } = useTranslation()
- // Determine what value to copy
- const valueToString = typeof value === 'string' ? value : String(value || '')
- const finalCopyValue = copyValue || valueToString
-
- const { copied, copy, reset } = useClipboard()
-
- const handleCopy = () => {
- copy(finalCopyValue)
- onCopy?.(finalCopyValue)
- }
-
- const tooltipText = copied
- ? t(($) => $[`${prefixEmbedded}.copied`], { ns: 'appOverview' })
- : t(($) => $[`${prefixEmbedded}.copy`], { ns: 'appOverview' })
- /* v8 ignore next -- i18n test mock always returns a non-empty string; runtime fallback is defensive. -- @preserve */
- const safeTooltipText = tooltipText || ''
-
- return (
- <div className={cn('relative w-full', wrapperClassName)}>
- <input
- ref={ref}
- className={cn(
- 'w-full appearance-none border border-transparent bg-components-input-bg-normal py-1.75 text-components-input-text-filled caret-primary-600 outline-hidden placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs',
- 'rounded-lg px-3 system-sm-regular',
- showCopyButton && 'pr-8',
- inputProps.disabled &&
- 'cursor-not-allowed border-transparent bg-components-input-bg-disabled text-components-input-text-filled-disabled hover:border-transparent hover:bg-components-input-bg-disabled',
- inputProps.className,
- )}
- value={value}
- {...(({ size: _size, ...rest }) => rest)(inputProps)}
- />
- {showCopyButton && (
- <div className="absolute top-1/2 right-2 -translate-y-1/2">
- <Tooltip>
- <TooltipTrigger
- render={
- <IconButton
- size="xs"
- variant="ghost"
- aria-label={safeTooltipText}
- onClick={handleCopy}
- onMouseLeave={reset}
- >
- {copied ? (
- <span
- className="i-ri-clipboard-fill size-3.5 text-text-tertiary"
- aria-hidden="true"
- />
- ) : (
- <span
- className="i-ri-clipboard-line size-3.5 text-text-tertiary"
- aria-hidden="true"
- />
- )}
- </IconButton>
- }
- />
- <TooltipContent>{safeTooltipText}</TooltipContent>
- </Tooltip>
- </div>
- )}
- </div>
- )
- },
-)
-
-InputWithCopy.displayName = 'InputWithCopy'
-
-export default InputWithCopy
diff --git a/web/app/components/base/input/__tests__/index.spec.tsx b/web/app/components/base/input/__tests__/index.spec.tsx
deleted file mode 100644
index 3e45949bb90..00000000000
--- a/web/app/components/base/input/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import type { ChangeEvent } from 'react'
-import { fireEvent, render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import Input from '../index'
-
-describe('Input', () => {
- it('disables the input and hides its clear action', () => {
- render(<Input showClearIcon value="test" disabled />)
-
- expect(screen.getByRole('textbox')).toBeDisabled()
- expect(screen.queryByRole('button', { name: 'common.operation.clear' })).not.toBeInTheDocument()
- })
-
- it('clears an editable value', async () => {
- const user = userEvent.setup()
- const onClear = vi.fn()
- render(<Input showClearIcon value="test" onClear={onClear} />)
-
- await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))
-
- expect(onClear).toHaveBeenCalledOnce()
- })
-
- it('normalizes leading zeros while changing an initial numeric zero', () => {
- let changedValue = ''
- const onChange = vi.fn((event: ChangeEvent<HTMLInputElement>) => {
- changedValue = event.target.value
- })
- render(<Input type="number" value={0} onChange={onChange} />)
-
- fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '00042' } })
-
- expect(onChange).toHaveBeenCalledOnce()
- expect(changedValue).toBe('42')
- })
-
- it('normalizes leading zeros before forwarding blur', () => {
- const onChange = vi.fn()
- const onBlur = vi.fn()
- render(<Input type="number" defaultValue="0012" onChange={onChange} onBlur={onBlur} />)
-
- fireEvent.blur(screen.getByRole('spinbutton'))
-
- expect(onChange.mock.calls[0]![0].target.value).toBe('12')
- expect(onBlur.mock.calls[0]![0].target.value).toBe('12')
- })
-})
diff --git a/web/app/components/base/input/index.stories.tsx b/web/app/components/base/input/index.stories.tsx
deleted file mode 100644
index eb1b64d0fbd..00000000000
--- a/web/app/components/base/input/index.stories.tsx
+++ /dev/null
@@ -1,419 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import { useState } from 'react'
-import Input from '.'
-
-const meta = {
- title: 'Base/Data Entry/Input',
- component: Input,
- parameters: {
- layout: 'centered',
- docs: {
- description: {
- component:
- 'Input component with support for icons, clear button, validation states, and units. Includes automatic leading zero removal for number inputs.',
- },
- },
- },
- tags: ['autodocs'],
- argTypes: {
- size: {
- control: 'select',
- options: ['regular', 'large'],
- description: 'Input size',
- },
- type: {
- control: 'select',
- options: ['text', 'number', 'email', 'password', 'url', 'tel'],
- description: 'Input type',
- },
- placeholder: {
- control: 'text',
- description: 'Placeholder text',
- },
- disabled: {
- control: 'boolean',
- description: 'Disabled state',
- },
- destructive: {
- control: 'boolean',
- description: 'Error/destructive state',
- },
- showLeftIcon: {
- control: 'boolean',
- description: 'Show search icon on left',
- },
- showClearIcon: {
- control: 'boolean',
- description: 'Show clear button when input has value',
- },
- unit: {
- control: 'text',
- description: 'Unit text displayed on right (e.g., "px", "ms")',
- },
- },
-} satisfies Meta<typeof Input>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-// Interactive demo wrapper
-const InputDemo = (args: any) => {
- const [value, setValue] = useState(args.value || '')
-
- return (
- <div style={{ width: '400px' }}>
- <Input
- {...args}
- value={value}
- onChange={(e) => {
- setValue(e.target.value)
- console.log('Input changed:', e.target.value)
- }}
- onClear={() => {
- setValue('')
- console.log('Input cleared')
- }}
- />
- </div>
- )
-}
-
-// Default state
-export const Default: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- placeholder: 'Enter text...',
- type: 'text',
- },
-}
-
-// Large size
-export const LargeSize: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'large',
- placeholder: 'Enter text...',
- type: 'text',
- },
-}
-
-// With search icon
-export const WithSearchIcon: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- showLeftIcon: true,
- placeholder: 'Search...',
- type: 'text',
- },
-}
-
-// With clear button
-export const WithClearButton: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- showClearIcon: true,
- value: 'Some text to clear',
- placeholder: 'Type something...',
- type: 'text',
- },
-}
-
-// Search input (icon + clear)
-export const SearchInput: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- showLeftIcon: true,
- showClearIcon: true,
- value: '',
- placeholder: 'Search...',
- type: 'text',
- },
-}
-
-// Disabled state
-export const Disabled: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- value: 'Disabled input',
- disabled: true,
- type: 'text',
- },
-}
-
-// Destructive/error state
-export const DestructiveState: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- value: 'invalid@email',
- destructive: true,
- placeholder: 'Enter email...',
- type: 'email',
- },
-}
-
-// Number input
-export const NumberInput: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- type: 'number',
- placeholder: 'Enter a number...',
- value: '0',
- },
-}
-
-// With unit
-export const WithUnit: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- type: 'number',
- value: '100',
- unit: 'px',
- placeholder: 'Enter value...',
- },
-}
-
-// Email input
-export const EmailInput: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- type: 'email',
- placeholder: 'Enter your email...',
- showClearIcon: true,
- },
-}
-
-// Password input
-export const PasswordInput: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- type: 'password',
- placeholder: 'Enter password...',
- value: 'secret123',
- },
-}
-
-// Size comparison
-const SizeComparisonDemo = () => {
- const [regularValue, setRegularValue] = useState('')
- const [largeValue, setLargeValue] = useState('')
-
- return (
- <div className="flex flex-col gap-6" style={{ width: '400px' }}>
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-gray-700">Regular Size</label>
- <Input
- size="regular"
- value={regularValue}
- onChange={(e) => setRegularValue(e.target.value)}
- placeholder="Regular input..."
- showClearIcon
- onClear={() => setRegularValue('')}
- />
- </div>
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-gray-700">Large Size</label>
- <Input
- size="large"
- value={largeValue}
- onChange={(e) => setLargeValue(e.target.value)}
- placeholder="Large input..."
- showClearIcon
- onClear={() => setLargeValue('')}
- />
- </div>
- </div>
- )
-}
-
-export const SizeComparison: Story = {
- render: () => <SizeComparisonDemo />,
-}
-
-// State comparison
-const StateComparisonDemo = () => {
- const [normalValue, setNormalValue] = useState('Normal state')
- const [errorValue, setErrorValue] = useState('Error state')
-
- return (
- <div className="flex flex-col gap-6" style={{ width: '400px' }}>
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-gray-700">Normal</label>
- <Input
- value={normalValue}
- onChange={(e) => setNormalValue(e.target.value)}
- showClearIcon
- onClear={() => setNormalValue('')}
- />
- </div>
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-gray-700">Destructive</label>
- <Input value={errorValue} onChange={(e) => setErrorValue(e.target.value)} destructive />
- </div>
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-gray-700">Disabled</label>
- <Input value="Disabled input" onChange={() => undefined} disabled />
- </div>
- </div>
- )
-}
-
-export const StateComparison: Story = {
- render: () => <StateComparisonDemo />,
-}
-
-// Form example
-const FormExampleDemo = () => {
- const [formData, setFormData] = useState({
- name: '',
- email: '',
- age: '',
- website: '',
- })
- const [errors, setErrors] = useState({
- email: false,
- age: false,
- })
-
- const validateEmail = (email: string) => {
- return /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(email)
- }
-
- return (
- <div style={{ width: '500px' }} className="rounded-lg border border-gray-200 bg-white p-6">
- <h3 className="mb-4 text-lg font-semibold">User Profile</h3>
- <div className="flex flex-col gap-4">
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-gray-700">Name</label>
- <Input
- value={formData.name}
- onChange={(e) => setFormData({ ...formData, name: e.target.value })}
- placeholder="Enter your name..."
- showClearIcon
- onClear={() => setFormData({ ...formData, name: '' })}
- />
- </div>
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-gray-700">Email</label>
- <Input
- type="email"
- value={formData.email}
- onChange={(e) => {
- setFormData({ ...formData, email: e.target.value })
- setErrors({
- ...errors,
- email: e.target.value ? !validateEmail(e.target.value) : false,
- })
- }}
- placeholder="Enter your email..."
- destructive={errors.email}
- showClearIcon
- onClear={() => {
- setFormData({ ...formData, email: '' })
- setErrors({ ...errors, email: false })
- }}
- />
- {errors.email && (
- <span className="text-xs text-red-600">Please enter a valid email address</span>
- )}
- </div>
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-gray-700">Age</label>
- <Input
- type="number"
- value={formData.age}
- onChange={(e) => {
- setFormData({ ...formData, age: e.target.value })
- setErrors({ ...errors, age: e.target.value ? Number(e.target.value) < 18 : false })
- }}
- placeholder="Enter your age..."
- destructive={errors.age}
- unit="years"
- />
- {errors.age && <span className="text-xs text-red-600">Must be 18 or older</span>}
- </div>
- <div className="flex flex-col gap-2">
- <label className="text-sm font-medium text-gray-700">Website</label>
- <Input
- type="url"
- value={formData.website}
- onChange={(e) => setFormData({ ...formData, website: e.target.value })}
- placeholder="https://example.com"
- showClearIcon
- onClear={() => setFormData({ ...formData, website: '' })}
- />
- </div>
- </div>
- </div>
- )
-}
-
-export const FormExample: Story = {
- render: () => <FormExampleDemo />,
-}
-
-// Search example
-const SearchExampleDemo = () => {
- const [searchQuery, setSearchQuery] = useState('')
- const items = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig', 'Grape']
- const filteredItems = items.filter((item) =>
- item.toLowerCase().includes(searchQuery.toLowerCase()),
- )
-
- return (
- <div style={{ width: '400px' }} className="flex flex-col gap-4">
- <Input
- size="large"
- showLeftIcon
- showClearIcon
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- onClear={() => setSearchQuery('')}
- placeholder="Search fruits..."
- />
- {searchQuery && (
- <div className="rounded-lg bg-gray-50 p-4">
- <div className="mb-2 text-xs text-gray-500">
- {filteredItems.length} result
- {filteredItems.length !== 1 ? 's' : ''}
- </div>
- <div className="flex flex-col gap-1">
- {filteredItems.map((item) => (
- <div key={item} className="text-sm text-gray-700">
- {item}
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- )
-}
-
-export const SearchExample: Story = {
- render: () => <SearchExampleDemo />,
-}
-
-// Interactive playground
-export const Playground: Story = {
- render: (args) => <InputDemo {...args} />,
- args: {
- size: 'regular',
- type: 'text',
- placeholder: 'Type something...',
- disabled: false,
- destructive: false,
- showLeftIcon: false,
- showClearIcon: true,
- unit: '',
- },
-}
diff --git a/web/app/components/base/input/index.tsx b/web/app/components/base/input/index.tsx
deleted file mode 100644
index 2db9fdee345..00000000000
--- a/web/app/components/base/input/index.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-import type { VariantProps } from 'class-variance-authority'
-import type { ChangeEventHandler, CSSProperties, FocusEventHandler } from 'react'
-import { cn } from '@langgenius/dify-ui/cn'
-import { cva } from 'class-variance-authority'
-import { noop } from 'es-toolkit/function'
-import * as React from 'react'
-import { useTranslation } from 'react-i18next'
-import { CopyFeedback } from '../copy-feedback'
-
-const inputVariants = cva('', {
- variants: {
- size: {
- regular: 'rounded-lg px-3 system-sm-regular',
- large: 'rounded-[10px] px-4 system-md-regular',
- },
- },
- defaultVariants: {
- size: 'regular',
- },
-})
-
-/**
- * @deprecated Use `@langgenius/dify-ui/input` for primitive inputs and
- * `@langgenius/dify-ui/field` for form composition. Search inputs should use
- * a dedicated composition built on the primitive input.
- */
-export type InputProps = {
- showLeftIcon?: boolean
- showClearIcon?: boolean
- showCopyIcon?: boolean
- onClear?: () => void
- disabled?: boolean
- destructive?: boolean
- wrapperClassName?: string
- styleCss?: CSSProperties
- unit?: string
-} & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size'> &
- VariantProps<typeof inputVariants>
-
-const removeLeadingZeros = (value: string) => value.replace(/^(-?)0+(?=\d)/, '$1')
-
-/**
- * @deprecated Use `@langgenius/dify-ui/input` for primitive inputs and
- * `@langgenius/dify-ui/field` for form composition. Search inputs should use
- * a dedicated composition built on the primitive input.
- */
-const Input = React.forwardRef<HTMLInputElement, InputProps>(
- (
- {
- size,
- disabled,
- destructive,
- showLeftIcon,
- showClearIcon,
- showCopyIcon,
- onClear,
- wrapperClassName,
- className,
- styleCss,
- value,
- placeholder,
- onChange = noop,
- onBlur = noop,
- unit,
- ...props
- },
- ref,
- ) => {
- const { t } = useTranslation()
- const handleNumberChange: ChangeEventHandler<HTMLInputElement> = (e) => {
- if (value === 0) {
- // remove leading zeros
- const formattedValue = removeLeadingZeros(e.target.value)
- if (e.target.value !== formattedValue) e.target.value = formattedValue
- }
- onChange(e)
- }
- const handleNumberBlur: FocusEventHandler<HTMLInputElement> = (e) => {
- // remove leading zeros
- const formattedValue = removeLeadingZeros(e.target.value)
- if (e.target.value !== formattedValue) {
- e.target.value = formattedValue
- onChange({
- ...e,
- type: 'change',
- target: {
- ...e.target,
- value: formattedValue,
- },
- })
- }
- onBlur(e)
- }
- return (
- <div className={cn('relative w-full', wrapperClassName)}>
- {showLeftIcon && (
- <span
- className={cn(
- 'absolute top-1/2 left-2 i-ri-search-line size-4 -translate-y-1/2 text-components-input-text-placeholder',
- )}
- />
- )}
- <input
- ref={ref}
- style={styleCss}
- className={cn(
- 'w-full appearance-none border border-transparent bg-components-input-bg-normal py-1.75 text-components-input-text-filled caret-primary-600 outline-hidden placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs',
- inputVariants({ size }),
- showLeftIcon && 'pl-6.5',
- showLeftIcon && size === 'large' && 'pl-7',
- showClearIcon && value && 'pr-6.5',
- showClearIcon && value && size === 'large' && 'pr-7',
- (destructive || showCopyIcon) && 'pr-6.5',
- (destructive || showCopyIcon) && size === 'large' && 'pr-7',
- disabled &&
- 'cursor-not-allowed border-transparent bg-components-input-bg-disabled text-components-input-text-filled-disabled hover:border-transparent hover:bg-components-input-bg-disabled',
- destructive &&
- 'border-components-input-border-destructive bg-components-input-bg-destructive text-components-input-text-filled hover:border-components-input-border-destructive hover:bg-components-input-bg-destructive focus:border-components-input-border-destructive focus:bg-components-input-bg-destructive',
- className,
- )}
- placeholder={
- placeholder ??
- (showLeftIcon
- ? t(($) => $['operation.search'], { ns: 'common' }) || ''
- : t(($) => $['placeholder.input'], { ns: 'common' }) || '')
- }
- value={value}
- onChange={props.type === 'number' ? handleNumberChange : onChange}
- onBlur={props.type === 'number' ? handleNumberBlur : onBlur}
- disabled={disabled}
- {...props}
- />
- {!!(showClearIcon && value && !disabled && !destructive) && (
- <button
- type="button"
- aria-label={t(($) => $['operation.clear'], { ns: 'common' })}
- className={cn(
- 'group absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer border-none bg-transparent p-px',
- )}
- onClick={onClear}
- >
- <span
- className="i-ri-close-circle-fill size-3.5 cursor-pointer text-text-quaternary group-hover:text-text-tertiary"
- aria-hidden="true"
- />
- </button>
- )}
- {destructive && (
- <span className="absolute top-1/2 right-2 i-ri-error-warning-line size-4 -translate-y-1/2 text-text-destructive-secondary" />
- )}
- {showCopyIcon && (
- <div className={cn('group absolute top-1/2 right-0 -translate-y-1/2 cursor-pointer')}>
- <CopyFeedback content={String(value ?? '')} className="size-7! hover:bg-transparent" />
- </div>
- )}
- {unit && (
- <div className="absolute top-1/2 right-2 -translate-y-1/2 system-sm-regular text-text-tertiary">
- {unit}
- </div>
- )}
- </div>
- )
- },
-)
-
-Input.displayName = 'Input'
-
-export default Input
diff --git a/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx
index 103f5d4d942..9eeecf99ae2 100644
--- a/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx
+++ b/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import dayjs from '@/app/components/base/date-and-time-picker/utils/dayjs'
import MarkdownForm from '../form'
@@ -369,27 +369,23 @@ describe('MarkdownForm', () => {
})
})
- // Native submit event is intentionally blocked at form level.
describe('Form submit behavior', () => {
- it('should prevent native submit propagation from form onSubmit', () => {
+ it('should submit with Enter without submitting the surrounding chat', async () => {
+ const user = userEvent.setup()
const parentOnSubmit = vi.fn()
const node = createRootNode([
createElementNode('input', { type: 'text', name: 'name', value: 'Alice' }),
createElementNode('button', {}, [createTextNode('Submit')]),
])
- const { container } = render(
+ render(
<div onSubmit={parentOnSubmit}>
<MarkdownForm node={node} />
</div>,
)
- const form = container.querySelector('form')
- expect(form).not.toBeNull()
- if (!form) throw new Error('Form element not found')
-
- fireEvent.submit(form)
+ await user.type(screen.getByRole('textbox', { name: 'name' }), '{Enter}')
expect(parentOnSubmit).not.toHaveBeenCalled()
- expect(mockOnSend).not.toHaveBeenCalled()
+ expect(mockOnSend).toHaveBeenCalledExactlyOnceWith('name: Alice')
})
})
@@ -820,7 +816,6 @@ describe('MarkdownForm', () => {
})
})
- // Standard input types (password, email, number) use the generic Input branch.
describe('Standard input types', () => {
it('should render password input with masked value', () => {
const node = createRootNode([
@@ -843,14 +838,22 @@ describe('MarkdownForm', () => {
expect(screen.getByPlaceholderText('Email'))!.toHaveAttribute('type', 'email')
})
- it('should render number input', () => {
+ it('should submit an edited decimal without changing the string output contract', async () => {
+ const user = userEvent.setup()
const node = createRootNode([
- createElementNode('input', { type: 'number', name: 'age', placeholder: 'Age' }),
+ createElementNode('label', { for: 'amount' }, [createTextNode('Amount')]),
+ createElementNode('input', { type: 'number', name: 'amount', value: '0' }),
+ createElementNode('button', {}, [createTextNode('Submit')]),
])
render(<MarkdownForm node={node} />)
- expect(screen.getByPlaceholderText('Age'))!.toHaveAttribute('type', 'number')
+ const input = screen.getByRole('textbox', { name: 'Amount' })
+ expect(input).toHaveValue('0')
+ await user.clear(input)
+ await user.type(input, '3.5')
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
+ expect(mockOnSend).toHaveBeenCalledExactlyOnceWith('amount: 3.5')
})
it('should submit typed value from password input', async () => {
diff --git a/web/app/components/base/markdown-blocks/form.tsx b/web/app/components/base/markdown-blocks/form.tsx
index eab848e9203..079d6b19186 100644
--- a/web/app/components/base/markdown-blocks/form.tsx
+++ b/web/app/components/base/markdown-blocks/form.tsx
@@ -1,6 +1,8 @@
import type { Dayjs } from 'dayjs'
import { Button } from '@langgenius/dify-ui/button'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
+import { Input } from '@langgenius/dify-ui/input'
+import { NumberField, NumberFieldGroup, NumberFieldInput } from '@langgenius/dify-ui/number-field'
import {
Select,
SelectContent,
@@ -12,7 +14,7 @@ import {
} from '@langgenius/dify-ui/select'
import { Textarea } from '@langgenius/dify-ui/textarea'
import * as React from 'react'
-import { useCallback, useMemo, useState } from 'react'
+import { useCallback, useId, useMemo, useState } from 'react'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'
import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'
@@ -20,7 +22,6 @@ import {
formatDateForOutput,
toDayjs,
} from '@/app/components/base/date-and-time-picker/utils/dayjs'
-import Input from '@/app/components/base/input'
import { MARKDOWN_FORM_FIELD_NAME_EXTRA_CHARS, MARKDOWN_FORM_FIELD_NAME_MAX_LENGTH } from '@/config'
import { getMarkdownButtonAppearance } from './button-appearance'
@@ -96,7 +97,7 @@ type HastElement = {
children: Array<HastElement | HastText>
}
-type FormValue = string | boolean | Dayjs | undefined
+type FormValue = string | number | boolean | Dayjs | undefined
type FormValues = Record<string, FormValue>
type EditState = {
source: HastElement[]
@@ -161,6 +162,7 @@ function getElementKey(child: HastElement, index: number): string {
}
const MarkdownForm = ({ node }: { node: HastElement }) => {
+ const formId = useId()
const typedNode = node
const { onSend } = useChatContext()
const [isSubmitting, setIsSubmitting] = useState(false)
@@ -223,8 +225,9 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {
}, [elementChildren, formValues])
const onSubmit = useCallback(
- (e: React.MouseEvent) => {
+ (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
+ e.stopPropagation()
if (isSubmitting) return
setIsSubmitting(true)
try {
@@ -246,21 +249,14 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {
)
return (
- <form
- autoComplete="off"
- className="flex flex-col self-stretch"
- onSubmit={(e) => {
- e.preventDefault()
- e.stopPropagation()
- }}
- >
+ <form autoComplete="off" className="flex flex-col self-stretch" onSubmit={onSubmit}>
{elementChildren.map((child, index) => {
const key = getElementKey(child, index)
if (child.tagName === SUPPORTED_TAGS.LABEL) {
return (
<label
key={key}
- htmlFor={getLabelTarget(child)}
+ htmlFor={`${formId}-${getLabelTarget(child)}`}
className="my-2 system-md-semibold text-text-secondary"
>
{getTextContent(child)}
@@ -276,6 +272,12 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {
if (!isSafeName(name)) return null
const type = str(child.properties.type) as SupportedType
+ const controlId = `${formId}-${str(child.properties.id) || name}`
+ const hasExternalLabel = elementChildren.some(
+ (node) =>
+ node.tagName === SUPPORTED_TAGS.LABEL &&
+ getLabelTarget(node) === (str(child.properties.id) || name),
+ )
if (type === SUPPORTED_TYPES.DATE || type === SUPPORTED_TYPES.DATETIME) {
return (
@@ -300,14 +302,11 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {
}
if (type === SUPPORTED_TYPES.CHECKBOX) {
const label = str(child.properties.dataTip || child.properties['data-tip'])
- const hasExternalLabel = elementChildren.some(
- (node) => node.tagName === SUPPORTED_TAGS.LABEL && getLabelTarget(node) === name,
- )
const checkboxAriaLabel = label || (hasExternalLabel ? undefined : name)
return (
<div className="mt-2 flex h-6 items-center space-x-2" key={key}>
<Checkbox
- id={name}
+ id={controlId}
checked={!!formValues[name]}
aria-label={checkboxAriaLabel}
onCheckedChange={(checked) => updateValue(name, checked)}
@@ -340,7 +339,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {
if (val != null) updateValue(name, val)
}}
>
- <SelectTrigger className="w-full">
+ <SelectTrigger id={controlId} aria-label={hasExternalLabel ? undefined : name}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -366,14 +365,37 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {
)
}
+ if (type === SUPPORTED_TYPES.NUMBER) {
+ const value = formValues[name]
+ return (
+ <NumberField
+ key={key}
+ name={name}
+ step="any"
+ value={value == null || value === '' ? null : Number(value)}
+ onValueChange={(value) => updateValue(name, value ?? '')}
+ >
+ <NumberFieldGroup>
+ <NumberFieldInput
+ id={controlId}
+ aria-label={hasExternalLabel ? undefined : name}
+ placeholder={str(child.properties.placeholder)}
+ />
+ </NumberFieldGroup>
+ </NumberField>
+ )
+ }
+
return (
<Input
key={key}
+ id={controlId}
+ aria-label={hasExternalLabel ? undefined : name}
type={type}
name={name}
placeholder={str(child.properties.placeholder)}
value={str(formValues[name])}
- onChange={(e) => updateValue(name, e.target.value)}
+ onValueChange={(value) => updateValue(name, value)}
/>
)
}
@@ -381,9 +403,16 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {
if (child.tagName === SUPPORTED_TAGS.TEXTAREA) {
const name = str(child.properties.name)
if (!isSafeName(name)) return null
+ const controlId = `${formId}-${str(child.properties.id) || name}`
+ const hasExternalLabel = elementChildren.some(
+ (node) =>
+ node.tagName === SUPPORTED_TAGS.LABEL &&
+ getLabelTarget(node) === (str(child.properties.id) || name),
+ )
return (
<Textarea
- aria-label={name}
+ id={controlId}
+ aria-label={hasExternalLabel ? undefined : name}
key={key}
name={name}
placeholder={str(child.properties.placeholder)}
@@ -405,7 +434,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {
{...appearance}
className="mt-4"
disabled={isSubmitting}
- onClick={onSubmit}
+ type="submit"
>
<span className="text-[13px]">{getTextContent(child)}</span>
</Button>
diff --git a/web/app/components/datasets/create/step-two/components/__tests__/inputs.spec.tsx b/web/app/components/datasets/create/step-two/components/__tests__/inputs.spec.tsx
index de21bafd052..91b54eeba2c 100644
--- a/web/app/components/datasets/create/step-two/components/__tests__/inputs.spec.tsx
+++ b/web/app/components/datasets/create/step-two/components/__tests__/inputs.spec.tsx
@@ -1,173 +1,43 @@
import { fireEvent, render, screen } from '@testing-library/react'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import userEvent from '@testing-library/user-event'
import { DelimiterInput, MaxLengthInput, OverlapInput } from '../inputs'
-// i18n mock returns namespaced keys like "datasetCreation.stepTwo.separator"
-const ns = 'datasetCreation'
-
describe('DelimiterInput', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('should associate the separator label with its input', () => {
- render(<DelimiterInput />)
- expect(screen.getByRole('textbox', { name: `${ns}.stepTwo.separator` })).toBeInTheDocument()
- })
-
- it('should render text input with placeholder', () => {
- render(<DelimiterInput />)
- const input = screen.getByPlaceholderText(`${ns}.stepTwo.separatorPlaceholder`)
- expect(input)!.toBeInTheDocument()
- expect(input)!.toHaveAttribute('type', 'text')
- })
-
- it('should pass through value and onChange props', () => {
- const onChange = vi.fn()
- render(<DelimiterInput value="test-val" onChange={onChange} />)
- expect(screen.getByDisplayValue('test-val'))!.toBeInTheDocument()
- })
-
- it('should render tooltip content', () => {
- render(<DelimiterInput />)
- expect(screen.getByLabelText(`${ns}.stepTwo.separatorTip`))!.toBeInTheDocument()
- })
-
- it('should suppress onChange during IME composition', () => {
- const onChange = vi.fn()
- const finalValue = 'wu'
- render(<DelimiterInput value="" onChange={onChange} />)
- const input = screen.getByPlaceholderText(`${ns}.stepTwo.separatorPlaceholder`)
+ it('commits the delimiter only after IME composition ends', () => {
+ const onValueChange = vi.fn()
+ render(<DelimiterInput value="" onValueChange={onValueChange} />)
+ const input = screen.getByRole('textbox', { name: 'datasetCreation.stepTwo.separator' })
fireEvent.compositionStart(input)
fireEvent.change(input, { target: { value: 'w' } })
- fireEvent.change(input, { target: { value: finalValue } })
- expect(onChange).not.toHaveBeenCalled()
+ fireEvent.change(input, { target: { value: '文' } })
+ expect(onValueChange).not.toHaveBeenCalled()
fireEvent.compositionEnd(input)
- expect(onChange).toHaveBeenCalledTimes(1)
- expect(onChange.mock.calls[0]![0].target.value).toBe(finalValue)
+ expect(onValueChange).toHaveBeenCalledExactlyOnceWith('文')
})
})
-describe('MaxLengthInput', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('should render max length label', () => {
- render(<MaxLengthInput onChange={vi.fn()} />)
- expect(screen.getByText(`${ns}.stepTwo.maxLength`))!.toBeInTheDocument()
- })
-
- it('should render number input', () => {
- render(<MaxLengthInput onChange={vi.fn()} />)
- const input = screen.getByRole('textbox')
- expect(input)!.toBeInTheDocument()
- })
-
- it('should accept value prop', () => {
- render(<MaxLengthInput value={500} onChange={vi.fn()} />)
- expect(screen.getByRole('textbox'))!.toHaveValue('500')
- })
-
- it('should have min of 1', () => {
- render(<MaxLengthInput onChange={vi.fn()} />)
- const input = screen.getByRole('textbox')
- expect(input)!.toBeInTheDocument()
- })
-
- it('should reset to the minimum when users clear the value', () => {
+describe.each([
+ { Component: MaxLengthInput, label: 'datasetCreation.stepTwo.maxLength' },
+ { Component: OverlapInput, label: 'datasetCreation.stepTwo.overlap' },
+])('$label', ({ Component, label }) => {
+ it('resets to the minimum when users clear the value', async () => {
+ const user = userEvent.setup()
const onChange = vi.fn()
- render(<MaxLengthInput value={500} onChange={onChange} />)
- fireEvent.change(screen.getByRole('textbox'), { target: { value: '' } })
- expect(onChange).toHaveBeenCalledWith(1)
- })
+ render(<Component value={50} onChange={onChange} />)
- it('should clamp out-of-range text edits before updating state', () => {
- const onChange = vi.fn()
- render(<MaxLengthInput value={500} max={1000} onChange={onChange} />)
-
- fireEvent.change(screen.getByRole('textbox'), { target: { value: '1200' } })
- expect(onChange).toHaveBeenLastCalledWith(1000)
- })
-})
-
-describe('OverlapInput', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('should render overlap label', () => {
- render(<OverlapInput onChange={vi.fn()} />)
- expect(screen.getAllByText(new RegExp(`${ns}.stepTwo.overlap`)).length).toBeGreaterThan(0)
- expect(screen.getByLabelText(`${ns}.stepTwo.overlapTip`))!.toBeInTheDocument()
- })
-
- it('should render number input', () => {
- render(<OverlapInput onChange={vi.fn()} />)
- const input = screen.getByRole('textbox')
- expect(input)!.toBeInTheDocument()
+ await user.clear(screen.getByRole('textbox', { name: label }))
+ expect(onChange).toHaveBeenLastCalledWith(1)
})
- it('should accept value prop', () => {
- render(<OverlapInput value={50} onChange={vi.fn()} />)
- expect(screen.getByRole('textbox'))!.toHaveValue('50')
- })
-
- it('should have min of 1', () => {
- render(<OverlapInput onChange={vi.fn()} />)
- const input = screen.getByRole('textbox')
- expect(input)!.toBeInTheDocument()
- })
-
- it('should reset to the minimum when users clear the value', () => {
- const onChange = vi.fn()
- render(<OverlapInput value={50} onChange={onChange} />)
- fireEvent.change(screen.getByRole('textbox'), { target: { value: '' } })
- expect(onChange).toHaveBeenCalledWith(1)
- })
-
- it('should clamp out-of-range text edits before updating state', () => {
+ it('clamps out-of-range edits before updating chunk settings', async () => {
+ const user = userEvent.setup()
const onChange = vi.fn()
- render(<OverlapInput value={50} max={100} onChange={onChange} />)
+ render(<Component value={50} max={100} onChange={onChange} />)
- fireEvent.change(screen.getByRole('textbox'), { target: { value: '150' } })
+ await user.tripleClick(screen.getByRole('textbox', { name: label }))
+ await user.paste('150')
expect(onChange).toHaveBeenLastCalledWith(100)
})
})
-
-// Regression: dify issue 39592 — in a narrow card the number inputs collapsed
-// to a 32px, unusable sliver. The fix reflows on the container (a
-// @container/chunkfields ancestor, see general-chunking-options): below 552px
-// each field stacks and is capped at max-w-[288px] so the input reads as a form
-// field; at/above 552px it restores flex-1 (three across, pixel-identical to
-// stock). The input keeps a min-width floor as the belt against re-collapse.
-// jsdom has no layout engine, so we cannot assert pixel widths — we assert the
-// structural classes. These fail before this change and pass after.
-describe('#39592 narrow-container regression (structural)', () => {
- it('gives the MaxLength input a min-width floor so it can never collapse to a sliver', () => {
- render(<MaxLengthInput onChange={vi.fn()} />)
- const input = screen.getByRole('textbox')
- expect(input.className).toContain('min-w-16')
- })
-
- it('gives the OverlapInput input a min-width floor too', () => {
- render(<OverlapInput onChange={vi.fn()} />)
- const input = screen.getByRole('textbox')
- expect(input.className).toContain('min-w-16')
- })
-
- it('caps each field width when stacked and restores flex-1 across the 552px container query', () => {
- render(<MaxLengthInput onChange={vi.fn()} />)
- const field = screen.getByRole('textbox').closest('.space-y-2')
- expect(field).not.toBeNull()
- // stacked (default / below threshold): constrained width, no stretch
- expect(field!.className).toContain('max-w-[288px]')
- // three-across (at/above threshold): restore flex-1 and drop the cap
- expect(field!.className).toContain('@min-[552px]/chunkfields:flex-1')
- expect(field!.className).toContain('@min-[552px]/chunkfields:max-w-none')
- // the previous flex-wrap approach is gone
- expect(field!.className).not.toContain('basis-[176px]')
- })
-})
diff --git a/web/app/components/datasets/create/step-two/components/general-chunking-options.tsx b/web/app/components/datasets/create/step-two/components/general-chunking-options.tsx
index e8f53abb61f..0a2a44a96ee 100644
--- a/web/app/components/datasets/create/step-two/components/general-chunking-options.tsx
+++ b/web/app/components/datasets/create/step-two/components/general-chunking-options.tsx
@@ -131,10 +131,7 @@ export const GeneralChunkingOptions: FC<GeneralChunkingOptionsProps> = ({
{/* Container query, not a viewport breakpoint: three across at/above a
552px container, stacked one-per-row below (see inputs.tsx FormField). */}
<div className="flex flex-col gap-3 @min-[552px]/chunkfields:flex-row">
- <DelimiterInput
- value={segmentIdentifier}
- onChange={(e) => onSegmentIdentifierChange(e.target.value)}
- />
+ <DelimiterInput value={segmentIdentifier} onValueChange={onSegmentIdentifierChange} />
<MaxLengthInput
unit="characters"
value={maxChunkLength}
diff --git a/web/app/components/datasets/create/step-two/components/inputs.tsx b/web/app/components/datasets/create/step-two/components/inputs.tsx
index dc092db1954..2f6cfc3595b 100644
--- a/web/app/components/datasets/create/step-two/components/inputs.tsx
+++ b/web/app/components/datasets/create/step-two/components/inputs.tsx
@@ -1,11 +1,12 @@
+import type { InputProps } from '@langgenius/dify-ui/input'
import type {
NumberFieldInputProps,
NumberFieldProps,
NumberFieldSize,
} from '@langgenius/dify-ui/number-field'
import type { FC, PropsWithChildren, ReactNode } from 'react'
-import type { InputProps } from '@/app/components/base/input'
import { cn } from '@langgenius/dify-ui/cn'
+import { Input } from '@langgenius/dify-ui/input'
import {
NumberField,
NumberFieldControls,
@@ -18,7 +19,6 @@ import {
import { useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Infotip } from '@/app/components/base/infotip'
-import Input from '@/app/components/base/input'
import { env } from '@/env'
const FormField: FC<PropsWithChildren<{ label: ReactNode }>> = (props) => {
@@ -35,12 +35,12 @@ const FormField: FC<PropsWithChildren<{ label: ReactNode }>> = (props) => {
)
}
-export const DelimiterInput: FC<InputProps & { tooltip?: string }> = ({
- tooltip,
- onChange,
- value,
- ...rest
-}) => {
+export const DelimiterInput: FC<
+ Omit<InputProps, 'onChange' | 'onValueChange'> & {
+ tooltip?: string
+ onValueChange?: (value: string) => void
+ }
+> = ({ tooltip, onValueChange, value, ...rest }) => {
const { t } = useTranslation()
const generatedInputId = useId()
const inputId = rest.id ?? generatedInputId
@@ -69,9 +69,9 @@ export const DelimiterInput: FC<InputProps & { tooltip?: string }> = ({
className="h-9"
placeholder={t(($) => $['stepTwo.separatorPlaceholder'], { ns: 'datasetCreation' })!}
value={isComposing.current ? compositionValue : value}
- onChange={(e) => {
- if (isComposing.current) setCompositionValue(e.target.value)
- else onChange?.(e)
+ onValueChange={(value) => {
+ if (isComposing.current) setCompositionValue(value)
+ else onValueChange?.(value)
}}
onCompositionStart={() => {
isComposing.current = true
@@ -81,10 +81,7 @@ export const DelimiterInput: FC<InputProps & { tooltip?: string }> = ({
const committed = e.currentTarget.value
isComposing.current = false
setCompositionValue('')
- onChange?.({
- ...e,
- target: { ...e.target, value: committed },
- } as unknown as React.ChangeEvent<HTMLInputElement>)
+ onValueChange?.(committed)
}}
{...rest}
/>
diff --git a/web/app/components/datasets/create/step-two/components/parent-child-options.tsx b/web/app/components/datasets/create/step-two/components/parent-child-options.tsx
index 1448e430394..8709e91708c 100644
--- a/web/app/components/datasets/create/step-two/components/parent-child-options.tsx
+++ b/web/app/components/datasets/create/step-two/components/parent-child-options.tsx
@@ -146,7 +146,7 @@ export const ParentChildOptions: FC<ParentChildOptionsProps> = ({
tooltip={t(($) => $['stepTwo.parentChildDelimiterTip'], {
ns: 'datasetCreation',
})!}
- onChange={(e) => onParentDelimiterChange(e.target.value)}
+ onValueChange={onParentDelimiterChange}
/>
<MaxLengthInput
unit="characters"
@@ -181,7 +181,7 @@ export const ParentChildOptions: FC<ParentChildOptionsProps> = ({
tooltip={t(($) => $['stepTwo.parentChildChunkDelimiterTip'], {
ns: 'datasetCreation',
})!}
- onChange={(e) => onChildDelimiterChange(e.target.value)}
+ onValueChange={onChildDelimiterChange}
/>
<MaxLengthInput
unit="characters"
diff --git a/web/app/components/tools/edit-custom-collection-modal/get-schema.tsx b/web/app/components/tools/edit-custom-collection-modal/get-schema.tsx
index c8a3e84298d..979afbb3e8e 100644
--- a/web/app/components/tools/edit-custom-collection-modal/get-schema.tsx
+++ b/web/app/components/tools/edit-custom-collection-modal/get-schema.tsx
@@ -7,11 +7,12 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
+import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { toast } from '@langgenius/dify-ui/toast'
import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Input from '@/app/components/base/input'
import { importSchemaFromURL } from '@/service/tools'
import examples from './examples'
@@ -25,6 +26,7 @@ const GetSchema: FC<Props> = ({ onChange }) => {
const [importUrl, setImportUrl] = useState('')
const [isParsing, setIsParsing] = useState(false)
const handleImportFromUrl = async () => {
+ if (isParsing) return
if (!importUrl.startsWith('http://') && !importUrl.startsWith('https://')) {
toast.error(t(($) => $['createTool.urlError'], { ns: 'tools' }))
return
@@ -44,35 +46,50 @@ const GetSchema: FC<Props> = ({ onChange }) => {
return (
<div className="flex w-56 justify-end gap-1">
- <DropdownMenu open={showImportFromUrl} onOpenChange={setShowImportFromUrl}>
- <DropdownMenuTrigger render={<Button size="small" />}>
+ <Popover open={showImportFromUrl} onOpenChange={setShowImportFromUrl}>
+ <PopoverTrigger render={<Button size="small" />}>
<span className="i-ri-add-line size-3" aria-hidden />
<span className="system-xs-medium text-text-secondary">
{t(($) => $['createTool.importFromUrl'], { ns: 'tools' })}
</span>
- </DropdownMenuTrigger>
- <DropdownMenuContent placement="bottom-start" sideOffset={2} className="w-75 p-2">
- <div className="relative">
- <Input
- type="text"
- className="w-full"
- placeholder={t(($) => $['createTool.importFromUrlPlaceHolder'], { ns: 'tools' })!}
- value={importUrl}
- onChange={(e) => setImportUrl(e.target.value)}
- />
- <Button
- className="absolute top-1 right-1"
- size="small"
- variant="primary"
- disabled={!importUrl}
- onClick={handleImportFromUrl}
- loading={isParsing}
- >
- {t(($) => $['operation.ok'], { ns: 'common' })}
- </Button>
- </div>
- </DropdownMenuContent>
- </DropdownMenu>
+ </PopoverTrigger>
+ <PopoverContent
+ placement="bottom-start"
+ sideOffset={2}
+ className="w-75 p-2"
+ aria-label={t(($) => $['createTool.importFromUrl'], { ns: 'tools' })}
+ >
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ void handleImportFromUrl()
+ }}
+ >
+ <InputGroup>
+ <InputGroupInput
+ type="text"
+ name="schemaUrl"
+ inputMode="url"
+ aria-label={t(($) => $['createTool.importFromUrl'], { ns: 'tools' })}
+ placeholder={t(($) => $['createTool.importFromUrlPlaceHolder'], { ns: 'tools' })!}
+ value={importUrl}
+ onValueChange={(value) => setImportUrl(value)}
+ />
+ <InputGroupAddon align="inline-end" className="pe-1">
+ <Button
+ type="submit"
+ size="small"
+ variant="primary"
+ disabled={!importUrl}
+ loading={isParsing}
+ >
+ {t(($) => $['operation.ok'], { ns: 'common' })}
+ </Button>
+ </InputGroupAddon>
+ </InputGroup>
+ </form>
+ </PopoverContent>
+ </Popover>
<DropdownMenu open={showExamples} onOpenChange={setShowExamples}>
<DropdownMenuTrigger render={<Button size="small" />}>
<span className="system-xs-medium text-text-secondary">
diff --git a/web/app/components/tools/edit-custom-collection-modal/test-api.tsx b/web/app/components/tools/edit-custom-collection-modal/test-api.tsx
index f5a20945aea..bcf0f5148ca 100644
--- a/web/app/components/tools/edit-custom-collection-modal/test-api.tsx
+++ b/web/app/components/tools/edit-custom-collection-modal/test-api.tsx
@@ -17,11 +17,11 @@ import {
DrawerTitle,
DrawerViewport,
} from '@langgenius/dify-ui/drawer'
+import { Input } from '@langgenius/dify-ui/input'
import { RiSettings2Line } from '@remixicon/react'
import * as React from 'react'
-import { useState } from 'react'
+import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Input from '@/app/components/base/input'
import { AuthType } from '@/app/components/tools/types'
import { useLocale } from '@/context/i18n'
import { getLanguage } from '@/i18n-config/language'
@@ -37,6 +37,7 @@ type Props = Readonly<{
const TestApi: FC<Props> = ({ positionCenter, customCollection, tool, onHide }) => {
const { t } = useTranslation()
+ const parameterId = useId()
const locale = useLocale()
const language = getLanguage(locale)
const [credentialsModalShow, setCredentialsModalShow] = useState(false)
@@ -104,23 +105,30 @@ const TestApi: FC<Props> = ({ positionCenter, customCollection, tool, onHide })
/>
</div>
</div>
- <div className="min-h-0 flex-1 overflow-y-auto px-6 pt-2">
+ <form
+ className="min-h-0 flex-1 overflow-y-auto px-6 pt-2"
+ onSubmit={(event) => {
+ event.preventDefault()
+ void handleTest()
+ }}
+ >
<div className="space-y-4">
<div>
<div className="py-2 system-sm-medium text-text-primary">
{t(($) => $['createTool.authMethod.title'], { ns: 'tools' })}
</div>
- <div
- className="flex h-9 cursor-pointer items-center justify-between rounded-lg bg-components-input-bg-normal px-2.5"
+ <button
+ type="button"
+ className="flex h-9 w-full cursor-pointer items-center justify-between rounded-lg bg-components-input-bg-normal px-2.5 outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"
onClick={() => setCredentialsModalShow(true)}
>
- <div className="system-xs-regular text-text-primary">
+ <span className="system-xs-regular text-text-primary">
{t(($) => $[`createTool.authMethod.types.${tempCredential.auth_type}`], {
ns: 'tools',
})}
- </div>
- <RiSettings2Line className="size-4 text-text-secondary" />
- </div>
+ </span>
+ <RiSettings2Line aria-hidden className="size-4 text-text-secondary" />
+ </button>
</div>
<div>
@@ -145,18 +153,24 @@ const TestApi: FC<Props> = ({ positionCenter, customCollection, tool, onHide })
key={index}
className="border-b border-divider-regular last:border-0"
>
- <td className="py-2 pr-2.5 pl-3">{item.label[language]}</td>
+ <td className="py-2 pr-2.5 pl-3">
+ <label htmlFor={`${parameterId}-${item.name}`}>
+ {item.label[language]}
+ </label>
+ </td>
<td className="">
<Input
+ id={`${parameterId}-${item.name}`}
+ name={item.name}
value={parametersValue[item.name] || ''}
- onChange={(e) =>
+ onValueChange={(value) =>
setParametersValue({
...parametersValue,
- [item.name]: e.target.value,
+ [item.name]: value,
})
}
type="text"
- className="border-transparent! bg-transparent!"
+ className="bg-transparent"
/>
</td>
</tr>
@@ -170,7 +184,7 @@ const TestApi: FC<Props> = ({ positionCenter, customCollection, tool, onHide })
variant="primary"
className="mt-4 h-10 w-full"
loading={testing}
- onClick={handleTest}
+ type="submit"
>
{t(($) => $['test.title'], { ns: 'tools' })}
</Button>
@@ -189,7 +203,7 @@ const TestApi: FC<Props> = ({ positionCenter, customCollection, tool, onHide })
)}
</div>
</div>
- </div>
+ </form>
</DrawerContent>
</DrawerPopup>
</DrawerViewport>
diff --git a/web/app/components/tools/workflow-tool/index.tsx b/web/app/components/tools/workflow-tool/index.tsx
index 3272dcf28c3..b09d1659f95 100644
--- a/web/app/components/tools/workflow-tool/index.tsx
+++ b/web/app/components/tools/workflow-tool/index.tsx
@@ -20,6 +20,8 @@ import {
DrawerTitle,
DrawerViewport,
} from '@langgenius/dify-ui/drawer'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { Input } from '@langgenius/dify-ui/input'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { toast } from '@langgenius/dify-ui/toast'
import { produce } from 'immer'
@@ -29,7 +31,6 @@ import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import AppIconPicker from '@/app/components/base/app-icon-picker'
import { Infotip } from '@/app/components/base/infotip'
-import Input from '@/app/components/base/input'
import LabelSelector from '@/app/components/tools/labels/selector'
import ConfirmModal from '@/app/components/tools/workflow-tool/confirm-modal'
import MethodSelector from '@/app/components/tools/workflow-tool/method-selector'
@@ -232,6 +233,7 @@ export function WorkflowToolDrawer({
onCreate,
}: WorkflowToolDrawerProps) {
const { t } = useTranslation()
+ const parameterId = React.useId()
const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false)
const [emoji, setEmoji] = useState<Emoji>(payload.icon)
@@ -323,14 +325,23 @@ export function WorkflowToolDrawer({
title={t(($) => $['common.workflowAsTool'], { ns: 'workflow' })!}
closeLabel={t(($) => $['operation.close'], { ns: 'common' })!}
>
- <div className="flex h-full flex-col">
+ <form
+ className="flex h-full flex-col"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (isAdd) onConfirm()
+ else setConfirmModalOpen(true)
+ }}
+ >
<div className="h-0 grow space-y-4 overflow-y-auto px-6 py-3">
{/* name & icon */}
- <div>
- <div className="py-2 system-sm-medium text-text-primary">
+ <Field name="label" className="gap-0">
+ <FieldLabel className="py-2 text-text-primary">
{t(($) => $['createTool.name'], { ns: 'tools' })}{' '}
- <span className="ml-1 text-red-500">*</span>
- </div>
+ <span aria-hidden className="ml-1 text-text-destructive">
+ *
+ </span>
+ </FieldLabel>
<div className="flex items-center justify-between gap-3">
<AppIcon
size="large"
@@ -343,18 +354,22 @@ export function WorkflowToolDrawer({
background={emoji.background}
/>
<Input
- className="h-10 grow"
+ className="h-10 min-w-0 flex-1"
placeholder={t(($) => $['createTool.toolNamePlaceHolder'], { ns: 'tools' })!}
value={label}
- onChange={(e) => setLabel(e.target.value)}
+ onValueChange={(value) => setLabel(value)}
/>
</div>
- </div>
+ </Field>
{/* name for tool call */}
- <div>
+ <Field name="name" className="gap-0" invalid={!isWorkflowToolNameValid(name)}>
<div className="flex items-center py-2 system-sm-medium text-text-primary">
- {t(($) => $['createTool.nameForToolCall'], { ns: 'tools' })}{' '}
- <span className="ml-1 text-red-500">*</span>
+ <FieldLabel className="py-0 text-text-primary">
+ {t(($) => $['createTool.nameForToolCall'], { ns: 'tools' })}
+ </FieldLabel>
+ <span aria-hidden className="ml-1 text-text-destructive">
+ *
+ </span>
<InfoTooltip>
{t(($) => $['createTool.nameForToolCallPlaceHolder'], { ns: 'tools' })}
</InfoTooltip>
@@ -363,28 +378,27 @@ export function WorkflowToolDrawer({
className="h-10"
placeholder={t(($) => $['createTool.nameForToolCallPlaceHolder'], { ns: 'tools' })!}
value={name}
- onChange={(e) => setName(e.target.value)}
+ onValueChange={(value) => setName(value)}
/>
{!isWorkflowToolNameValid(name) && (
- <div className="text-xs leading-4.5 text-red-500">
+ <FieldError match className="py-0 text-xs leading-4.5">
{t(($) => $['createTool.nameForToolCallTip'], { ns: 'tools' })}
- </div>
+ </FieldError>
)}
- </div>
+ </Field>
{/* description */}
- <div>
- <div className="py-2 system-sm-medium text-text-primary">
+ <Field name="description" className="gap-0">
+ <FieldLabel className="py-2 text-text-primary">
{t(($) => $['createTool.description'], { ns: 'tools' })}
- </div>
+ </FieldLabel>
<Textarea
- aria-label={t(($) => $['createTool.description'], { ns: 'tools' })}
placeholder={
t(($) => $['createTool.descriptionPlaceholder'], { ns: 'tools' }) || ''
}
value={description}
onValueChange={(value) => setDescription(value)}
/>
- </div>
+ </Field>
{/* Tool Input */}
<div>
<div className="py-2 system-sm-medium text-text-primary">
@@ -400,7 +414,7 @@ export function WorkflowToolDrawer({
<th className="w-25.5 p-2 pl-3 font-medium">
{t(($) => $['createTool.toolInput.method'], { ns: 'tools' })}
</th>
- <th className="p-2 pl-3 font-medium">
+ <th id={`${parameterId}-description`} className="p-2 pl-3 font-medium">
{t(($) => $['createTool.toolInput.description'], { ns: 'tools' })}
</th>
</tr>
@@ -411,7 +425,10 @@ export function WorkflowToolDrawer({
<td className="max-w-39 p-2 pl-3">
<div className="text-[13px] leading-4.5">
<div className="flex">
- <span className="truncate font-medium text-text-primary">
+ <span
+ id={`${parameterId}-${index}-name`}
+ className="truncate font-medium text-text-primary"
+ >
{item.name}
</span>
<span className="shrink-0 pl-1 text-xs leading-4.5 text-[#ec4a0a]">
@@ -451,7 +468,8 @@ export function WorkflowToolDrawer({
<td className="w-59 p-2 pl-3 text-text-tertiary">
<input
type="text"
- className="w-full appearance-none bg-transparent text-[13px] leading-4.5 font-normal text-text-secondary caret-primary-600 outline-hidden placeholder:text-text-quaternary"
+ aria-labelledby={`${parameterId}-${index}-name ${parameterId}-description`}
+ className="w-full appearance-none rounded-sm bg-transparent text-[13px] leading-4.5 font-normal text-text-secondary caret-primary-600 outline-hidden placeholder:text-text-quaternary focus-visible:ring-2 focus-visible:ring-state-accent-solid"
placeholder={t(
($) => $['createTool.toolInput.descriptionPlaceholder'],
{
@@ -527,19 +545,19 @@ export function WorkflowToolDrawer({
<LabelSelector value={labels} onChange={handleLabelSelect} />
</div>
{/* Privacy Policy */}
- <div>
- <div className="py-2 system-sm-medium text-text-primary">
+ <Field name="privacy_policy" className="gap-0">
+ <FieldLabel className="py-2 text-text-primary">
{t(($) => $['createTool.privacyPolicy'], { ns: 'tools' })}
- </div>
+ </FieldLabel>
<Input
className="h-10"
value={privacyPolicy}
- onChange={(e) => setPrivacyPolicy(e.target.value)}
+ onValueChange={(value) => setPrivacyPolicy(value)}
placeholder={
t(($) => $['createTool.privacyPolicyPlaceholder'], { ns: 'tools' }) || ''
}
/>
- </div>
+ </Field>
</div>
<div
className={cn(
@@ -554,18 +572,12 @@ export function WorkflowToolDrawer({
)}
<div className="flex space-x-2">
<Button onClick={onHide}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
- <Button
- variant="primary"
- onClick={() => {
- if (isAdd) onConfirm()
- else setConfirmModalOpen(true)
- }}
- >
+ <Button variant="primary" type="submit">
{t(($) => $['operation.save'], { ns: 'common' })}
</Button>
</div>
</div>
- </div>
+ </form>
</WorkflowToolDrawerFrame>
<AppIconPicker
open={showEmojiPicker}
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.helpers.spec.ts b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.helpers.spec.ts
index eeec24ec204..2b2ff79af17 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.helpers.spec.ts
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.helpers.spec.ts
@@ -12,7 +12,6 @@ import {
getCheckboxListValue,
getFilterVar,
getFormInputState,
- getNumberInputValue,
getSelectedLabels,
getTargetVarType,
getVarKindType,
@@ -178,11 +177,7 @@ describe('form-input-item helpers', () => {
expect(getCheckboxListValue(['alpha', 'missing'], ['beta'], options)).toEqual(['alpha'])
})
- it('should normalize number and variable selector values', () => {
- expect(getNumberInputValue(Number.NaN)).toBe('')
- expect(getNumberInputValue(2)).toBe(2)
- expect(getNumberInputValue('3')).toBe('3')
- expect(getNumberInputValue(undefined)).toBe('')
+ it('should normalize variable selector values', () => {
expect(normalizeVariableSelectorValue([])).toEqual([])
expect(normalizeVariableSelectorValue(['node', 'answer'])).toEqual(['node', 'answer'])
expect(normalizeVariableSelectorValue('')).toBe('')
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.spec.tsx
index 167d396ef25..f758681b541 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.spec.tsx
@@ -4,6 +4,7 @@ import type {
FormOption,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
import { fireEvent, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { VarKindType } from '../../types'
@@ -91,7 +92,23 @@ const renderFormInputItem = (props: Partial<ComponentProps<typeof FormInputItem>
}
describe('FormInputItem', () => {
- it('should parse number inputs as numbers', () => {
+ it('shows a schema-provided numeric string and prevents edits in readonly mode', async () => {
+ const user = userEvent.setup()
+ const { onChange } = renderFormInputItem({
+ readOnly: true,
+ schema: createSchema({ type: FormTypeEnum.textNumber }),
+ value: { field: { type: VarKindType.constant, value: '3.5' } },
+ })
+ const input = screen.getByRole('textbox')
+ expect(input).toHaveValue('3.5')
+ expect(input).toHaveAttribute('readonly')
+ await user.type(input, '9{ArrowUp}')
+ expect(onChange).not.toHaveBeenCalled()
+ expect(input).toHaveValue('3.5')
+ })
+
+ it('should store a numeric constant and clear it without producing NaN', async () => {
+ const user = userEvent.setup()
const { onChange } = renderFormInputItem({
schema: createSchema({ type: FormTypeEnum.textNumber }),
value: {
@@ -102,7 +119,9 @@ describe('FormInputItem', () => {
},
})
- fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '3.5' } })
+ const input = screen.getByRole('textbox')
+ await user.clear(input)
+ await user.type(input, '3.5')
expect(onChange).toHaveBeenCalledWith({
field: {
@@ -110,6 +129,10 @@ describe('FormInputItem', () => {
value: 3.5,
},
})
+ await user.clear(input)
+ expect(onChange).toHaveBeenLastCalledWith({
+ field: { type: VarKindType.constant, value: null },
+ })
})
it('should toggle boolean fields using the shared boolean input', () => {
diff --git a/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx b/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx
index 3e53916b6e4..129b3c3a3c9 100644
--- a/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx
+++ b/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx
@@ -3,6 +3,8 @@ import type { FC } from 'react'
import type { InputVar } from '../../../../types'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { cn } from '@langgenius/dify-ui/cn'
+import { Input } from '@langgenius/dify-ui/input'
+import { NumberField, NumberFieldGroup, NumberFieldInput } from '@langgenius/dify-ui/number-field'
import {
Select,
SelectContent,
@@ -23,7 +25,6 @@ import { Line3 } from '@/app/components/base/icons/src/public/common'
import { BubbleX } from '@/app/components/base/icons/src/vender/line/others'
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
import TextGenerationImageUploader from '@/app/components/base/image-uploader/text-generation-image-uploader'
-import Input from '@/app/components/base/input'
import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
import { VarBlockIcon } from '@/app/components/workflow/block-icon'
import { useHooksStore } from '@/app/components/workflow/hooks-store'
@@ -52,6 +53,7 @@ const FormItem: FC<Props> = ({
inStepRun = false,
}) => {
const { t } = useTranslation()
+ const labelId = React.useId()
const { type } = payload
const fileSettings = useHooksStore((s) => s.configsMap?.fileSettings)
const jsonSchemaPlaceholder = React.useMemo(() => {
@@ -144,7 +146,7 @@ const FormItem: FC<Props> = ({
<div className={cn(className)}>
{!isArrayLikeType && !isBooleanType && (
<div className="mb-1 flex h-6 items-center gap-1 system-sm-semibold text-text-secondary">
- <div className="truncate">
+ <div id={labelId} className="truncate">
{typeof payload.label === 'object' ? nodeKey : payload.label}
</div>
{payload.hide === true ? (
@@ -163,26 +165,37 @@ const FormItem: FC<Props> = ({
<div className="grow">
{type === InputVarType.textInput && (
<Input
+ name={payload.variable}
+ aria-labelledby={labelId}
value={value || ''}
- onChange={(e) => onChange(e.target.value)}
+ onValueChange={(value) => onChange(value)}
placeholder={typeof payload.label === 'object' ? payload.label.variable : payload.label}
autoFocus={autoFocus}
/>
)}
{type === InputVarType.number && (
- <Input
- type="number"
- value={value || ''}
- onChange={(e) => onChange(e.target.value)}
- placeholder={typeof payload.label === 'object' ? payload.label.variable : payload.label}
- autoFocus={autoFocus}
- />
+ <NumberField
+ step="any"
+ name={payload.variable}
+ value={value == null || value === '' ? null : Number(value)}
+ onValueChange={(value) => onChange(value)}
+ >
+ <NumberFieldGroup>
+ <NumberFieldInput
+ aria-labelledby={labelId}
+ placeholder={
+ typeof payload.label === 'object' ? payload.label.variable : payload.label
+ }
+ autoFocus={autoFocus}
+ />
+ </NumberFieldGroup>
+ </NumberField>
)}
{type === InputVarType.paragraph && (
<Textarea
- aria-label={typeof payload.label === 'object' ? payload.label.variable : payload.label}
+ aria-labelledby={labelId}
value={value || ''}
onValueChange={(value) => onChange(value)}
placeholder={typeof payload.label === 'object' ? payload.label.variable : payload.label}
diff --git a/web/app/components/workflow/nodes/_base/components/form-input-item.helpers.ts b/web/app/components/workflow/nodes/_base/components/form-input-item.helpers.ts
index 9d5e7f7c61a..3d1f0955d0e 100644
--- a/web/app/components/workflow/nodes/_base/components/form-input-item.helpers.ts
+++ b/web/app/components/workflow/nodes/_base/components/form-input-item.helpers.ts
@@ -239,12 +239,4 @@ export const getCheckboxListValue = (
return current.filter((item) => allowedValues.has(item))
}
-export const getNumberInputValue = (currentValue: unknown): number | string => {
- if (typeof currentValue === 'number') return Number.isNaN(currentValue) ? '' : currentValue
-
- if (typeof currentValue === 'string') return currentValue
-
- return ''
-}
-
export const normalizeVariableSelectorValue = (value: ValueSelector | string) => value || ''
diff --git a/web/app/components/workflow/nodes/_base/components/form-input-item.tsx b/web/app/components/workflow/nodes/_base/components/form-input-item.tsx
index 56dff0cf320..4e8a1235f84 100644
--- a/web/app/components/workflow/nodes/_base/components/form-input-item.tsx
+++ b/web/app/components/workflow/nodes/_base/components/form-input-item.tsx
@@ -11,6 +11,7 @@ import type { Event, Tool } from '@/app/components/tools/types'
import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'
import type { ToolWithProvider, ValueSelector, Var } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
+import { NumberField, NumberFieldGroup, NumberFieldInput } from '@langgenius/dify-ui/number-field'
import {
Select,
SelectContent,
@@ -22,7 +23,6 @@ import {
import { useSuspenseQuery } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react'
import { CheckboxList } from '@/app/components/base/checkbox-list'
-import Input from '@/app/components/base/input'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
import { AppSelector } from '@/app/components/plugins/plugin-detail-panel/app-selector'
import ModelParameterModal from '@/app/components/plugins/plugin-detail-panel/model-selector'
@@ -44,7 +44,6 @@ import {
getCheckboxListValue,
getFilterVar,
getFormInputState,
- getNumberInputValue,
getSelectedLabels,
getTargetVarType,
getVarKindType,
@@ -56,6 +55,7 @@ import FormInputTypeSwitch from './form-input-type-switch'
type Props = Readonly<{
readOnly: boolean
+ labelId?: string
nodeId: string
schema: CredentialFormSchema
value: ResourceVarInputs
@@ -81,6 +81,7 @@ type FormInputValue =
const FormInputItem: FC<Props> = ({
readOnly,
+ labelId,
nodeId,
schema,
value,
@@ -237,14 +238,12 @@ const FormInputItem: FC<Props> = ({
const handleValueChange = (newValue: FormInputValue) => {
const nextType = getVarKindType(formState) ?? varInput?.type ?? VarKindType.constant
- let nextValue: FormInputValue = newValue
- if (isNumber) nextValue = Number.parseFloat(String(newValue ?? ''))
onChange({
...value,
[variable]: {
...varInput,
type: nextType,
- value: nextValue,
+ value: newValue,
},
})
}
@@ -345,13 +344,20 @@ const FormInputItem: FC<Props> = ({
/>
)}
{isNumber && isConstant && (
- <Input
- className="h-8 grow"
- type="number"
- value={getNumberInputValue(varInput?.value)}
- onChange={(e) => handleValueChange(e.target.value)}
- placeholder={placeholder?.[language] || placeholder?.en_US}
- />
+ <NumberField
+ step="any"
+ className="min-w-0 grow"
+ value={varInput?.value == null || varInput.value === '' ? null : Number(varInput.value)}
+ readOnly={readOnly}
+ onValueChange={(value) => handleValueChange(value)}
+ >
+ <NumberFieldGroup>
+ <NumberFieldInput
+ aria-labelledby={labelId}
+ placeholder={placeholder?.[language] || placeholder?.en_US}
+ />
+ </NumberFieldGroup>
+ </NumberField>
)}
{isDate && isConstant && (
<div className="min-w-0 grow">
diff --git a/web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx
index 817149ecf2f..e6c3ca7cac6 100644
--- a/web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx
@@ -1,6 +1,6 @@
import type { AssignerNodeOperation, AssignerNodeType } from '../types'
import type { PanelProps } from '@/types/workflow'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
@@ -288,10 +288,12 @@ describe('assigner path', () => {
/>,
)
- fireEvent.change(screen.getByDisplayValue('hello'), { target: { value: 'updated text' } })
+ await user.click(screen.getByRole('textbox', { name: 'node-1.count' }))
+ await user.keyboard('{Control>}a{/Control}')
+ await user.paste('updated text')
expect(onChange).toHaveBeenLastCalledWith(
[createOperation({ operation: WriteMode.set, value: 'updated text' })],
- 'updated text',
+ undefined,
)
onChange.mockClear()
@@ -311,10 +313,12 @@ describe('assigner path', () => {
/>,
)
- fireEvent.change(screen.getByDisplayValue('3'), { target: { value: '5' } })
+ await user.click(screen.getByRole('textbox', { name: 'node-1.count' }))
+ await user.keyboard('{Control>}a{/Control}')
+ await user.paste('5')
expect(onChange).toHaveBeenLastCalledWith(
[createOperation({ operation: WriteMode.set, value: 5 })],
- 5,
+ undefined,
)
onChange.mockClear()
@@ -337,7 +341,7 @@ describe('assigner path', () => {
await user.click(screen.getByRole('button', { name: 'bool:false' }))
expect(onChange).toHaveBeenLastCalledWith(
[createOperation({ operation: WriteMode.set, value: true })],
- true,
+ undefined,
)
onChange.mockClear()
@@ -357,10 +361,12 @@ describe('assigner path', () => {
/>,
)
- fireEvent.change(screen.getByLabelText('code-editor'), { target: { value: '{"a":2}' } })
+ await user.click(screen.getByRole('textbox', { name: 'code-editor' }))
+ await user.keyboard('{Control>}a{/Control}')
+ await user.paste('{"a":2}')
expect(onChange).toHaveBeenLastCalledWith(
[createOperation({ operation: WriteMode.set, value: '{"a":2}' })],
- '{"a":2}',
+ undefined,
)
onChange.mockClear()
@@ -380,10 +386,12 @@ describe('assigner path', () => {
/>,
)
- fireEvent.change(screen.getByDisplayValue('2'), { target: { value: '4' } })
+ await user.click(screen.getByRole('textbox', { name: 'node-1.count' }))
+ await user.keyboard('{Control>}a{/Control}')
+ await user.paste('4')
expect(onChange).toHaveBeenLastCalledWith(
[createOperation({ operation: WriteMode.increment, value: 4 })],
- 4,
+ undefined,
)
const buttons = screen.getAllByRole('button')
diff --git a/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/branches.spec.tsx b/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/branches.spec.tsx
index 60313505d70..b0562de18c1 100644
--- a/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/branches.spec.tsx
+++ b/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/branches.spec.tsx
@@ -1,5 +1,5 @@
import type { ComponentProps } from 'react'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { VarType } from '@/app/components/workflow/types'
import { AssignerNodeInputType, WriteMode } from '../../../types'
@@ -142,7 +142,8 @@ describe('assigner/var-list branches', () => {
])
})
- it('updates string and number constant inputs through the inline editors', () => {
+ it('updates string and number constant inputs through the inline editors', async () => {
+ const user = userEvent.setup()
const { handleChange, rerender } = renderVarList({
list: [
createOperation({
@@ -155,9 +156,8 @@ describe('assigner/var-list branches', () => {
getToAssignedVarType: () => VarType.number,
})
- fireEvent.change(screen.getByRole('spinbutton'), {
- target: { value: '2' },
- })
+ await user.clear(screen.getByRole('textbox', { name: 'node-a.flag' }))
+ await user.type(screen.getByRole('textbox', { name: 'node-a.flag' }), '2')
expect(handleChange).toHaveBeenLastCalledWith(
[
@@ -167,7 +167,7 @@ describe('assigner/var-list branches', () => {
value: 2,
}),
],
- 2,
+ undefined,
)
rerender(
@@ -191,9 +191,8 @@ describe('assigner/var-list branches', () => {
/>,
)
- fireEvent.change(screen.getByRole('textbox'), {
- target: { value: 'updated' },
- })
+ await user.tripleClick(screen.getByRole('textbox'))
+ await user.paste('updated')
expect(handleChange).toHaveBeenLastCalledWith(
[
@@ -203,11 +202,12 @@ describe('assigner/var-list branches', () => {
value: 'updated',
}),
],
- 'updated',
+ undefined,
)
})
- it('updates numeric write-mode inputs through the dedicated number field', () => {
+ it('updates numeric write-mode inputs through the dedicated number field', async () => {
+ const user = userEvent.setup()
const { handleChange } = renderVarList({
list: [
createOperation({
@@ -220,9 +220,8 @@ describe('assigner/var-list branches', () => {
writeModeTypesNum: [WriteMode.increment],
})
- fireEvent.change(screen.getByRole('spinbutton'), {
- target: { value: '5' },
- })
+ await user.clear(screen.getByRole('textbox', { name: 'node-a.flag' }))
+ await user.type(screen.getByRole('textbox', { name: 'node-a.flag' }), '5')
expect(handleChange).toHaveBeenLastCalledWith(
[
@@ -231,7 +230,7 @@ describe('assigner/var-list branches', () => {
value: 5,
}),
],
- 5,
+ undefined,
)
})
})
diff --git a/web/app/components/workflow/nodes/assigner/components/var-list/index.tsx b/web/app/components/workflow/nodes/assigner/components/var-list/index.tsx
index 35eafdb3573..d73e4d836c2 100644
--- a/web/app/components/workflow/nodes/assigner/components/var-list/index.tsx
+++ b/web/app/components/workflow/nodes/assigner/components/var-list/index.tsx
@@ -3,13 +3,13 @@ import type { FC } from 'react'
import type { AssignerNodeOperation } from '../../types'
import type { ValueSelector, Var } from '@/app/components/workflow/types'
import { IconButton } from '@langgenius/dify-ui/icon-button'
+import { NumberField, NumberFieldGroup, NumberFieldInput } from '@langgenius/dify-ui/number-field'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { noop } from 'es-toolkit/function'
import { produce } from 'immer'
import * as React from 'react'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
-import Input from '@/app/components/base/input'
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
import ListNoDataPlaceholder from '@/app/components/workflow/nodes/_base/components/list-no-data-placeholder'
import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
@@ -93,9 +93,9 @@ const VarList: FC<Props> = ({
(index: number) => {
return (value: ValueSelector | string | number | boolean) => {
const newList = produce(list, (draft) => {
- draft[index]!.value = value as ValueSelector
+ draft[index]!.value = value
})
- onChange(newList, value as ValueSelector)
+ onChange(newList, Array.isArray(value) ? value : undefined)
}
},
[list, onChange],
@@ -214,14 +214,6 @@ const VarList: FC<Props> = ({
)}
{!!(item.operation === WriteMode.set && assignedVarType) && (
<>
- {assignedVarType === 'number' && (
- <Input
- type="number"
- value={item.value as number}
- onChange={(e) => handleToAssignedVarChange(index)(Number(e.target.value))}
- className="w-full"
- />
- )}
{assignedVarType === 'string' && (
<Textarea
aria-label={
@@ -250,14 +242,29 @@ const VarList: FC<Props> = ({
)}
</>
)}
- {writeModeTypesNum?.includes(item.operation) && (
- <Input
- type="number"
- value={item.value as number}
- onChange={(e) => handleToAssignedVarChange(index)(Number(e.target.value))}
- placeholder="Enter number value..."
+ {((item.operation === WriteMode.set && assignedVarType === VarType.number) ||
+ writeModeTypesNum?.includes(item.operation)) && (
+ <NumberField
+ step="any"
+ value={typeof item.value === 'number' ? item.value : null}
+ readOnly={readonly}
+ onValueChange={(value) => handleToAssignedVarChange(index)(value ?? '')}
className="w-full"
- />
+ >
+ <NumberFieldGroup>
+ <NumberFieldInput
+ aria-label={
+ item.variable_selector.join('.') ||
+ t(($) => $['nodes.assigner.setParameter'], { ns: 'workflow' })
+ }
+ placeholder={
+ writeModeTypesNum?.includes(item.operation)
+ ? 'Enter number value...'
+ : undefined
+ }
+ />
+ </NumberFieldGroup>
+ </NumberField>
)}
</div>
<IconButton
diff --git a/web/app/components/workflow/nodes/http/components/authorization/index.tsx b/web/app/components/workflow/nodes/http/components/authorization/index.tsx
index 5d8cc329677..aa8aae946da 100644
--- a/web/app/components/workflow/nodes/http/components/authorization/index.tsx
+++ b/web/app/components/workflow/nodes/http/components/authorization/index.tsx
@@ -5,12 +5,12 @@ import type { Var } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { Input } from '@langgenius/dify-ui/input'
import { produce } from 'immer'
import * as React from 'react'
-import { useCallback, useState } from 'react'
+import { useCallback, useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import BaseInput from '@/app/components/base/input'
-import Input from '@/app/components/workflow/nodes/_base/components/input-support-select-var'
+import InputSupportSelectVar from '@/app/components/workflow/nodes/_base/components/input-support-select-var'
import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'
import { VarType } from '@/app/components/workflow/types'
import { APIType, AuthorizationType } from '../../types'
@@ -30,15 +30,17 @@ const Field = ({
title,
isRequired,
children,
+ htmlFor,
}: {
title: string
isRequired?: boolean
children: React.JSX.Element
+ htmlFor?: string
}) => {
return (
<div>
<div className="text-[13px] leading-8 font-medium text-text-secondary">
- {title}
+ {htmlFor ? <label htmlFor={htmlFor}>{title}</label> : title}
{isRequired && <span className="ml-0.5 text-text-destructive">*</span>}
</div>
<div>{children}</div>
@@ -48,6 +50,7 @@ const Field = ({
const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide }) => {
const { t } = useTranslation()
+ const headerId = useId()
const [isFocus, setIsFocus] = useState(false)
const { availableVars, availableNodesWithParent } = useAvailableVarList(nodeId, {
@@ -92,7 +95,7 @@ const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide })
const handleAPIKeyOrHeaderChange = useCallback(
(type: 'api_key' | 'header') => {
- return (e: React.ChangeEvent<HTMLInputElement>) => {
+ return (value: string) => {
const newPayload = produce(tempPayload, (draft: AuthorizationPayloadType) => {
if (!draft.config) {
draft.config = {
@@ -100,7 +103,7 @@ const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide })
api_key: '',
}
}
- draft.config[type] = e.target.value
+ draft.config[type] = value
})
setTempPayload(newPayload)
}
@@ -140,7 +143,12 @@ const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide })
{t(($) => $[`${i18nPrefix}.authorization`], { ns: 'workflow' })}
</DialogTitle>
- <div>
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ handleConfirm()
+ }}
+ >
<div className="space-y-2">
<Field title={t(($) => $[`${i18nPrefix}.authorizationType`], { ns: 'workflow' })}>
<RadioGroup
@@ -182,10 +190,16 @@ const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide })
/>
</Field>
{tempPayload.config?.type === APIType.custom && (
- <Field title={t(($) => $[`${i18nPrefix}.header`], { ns: 'workflow' })} isRequired>
- <BaseInput
+ <Field
+ htmlFor={headerId}
+ title={t(($) => $[`${i18nPrefix}.header`], { ns: 'workflow' })}
+ isRequired
+ >
+ <Input
+ id={headerId}
+ name="header"
value={tempPayload.config?.header || ''}
- onChange={handleAPIKeyOrHeaderChange('header')}
+ onValueChange={handleAPIKeyOrHeaderChange('header')}
/>
</Field>
)}
@@ -195,7 +209,7 @@ const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide })
isRequired
>
<div className="flex">
- <Input
+ <InputSupportSelectVar
instanceId="http-api-key"
className={cn(
isFocus
@@ -218,11 +232,11 @@ const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide })
</div>
<div className="mt-6 flex justify-end space-x-2">
<Button onClick={onHide}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
- <Button variant="primary" onClick={handleConfirm}>
+ <Button variant="primary" type="submit">
{t(($) => $['operation.save'], { ns: 'common' })}
</Button>
</div>
- </div>
+ </form>
</DialogContent>
</Dialog>
)
diff --git a/web/app/components/workflow/nodes/http/components/key-value/key-value-edit/item.tsx b/web/app/components/workflow/nodes/http/components/key-value/key-value-edit/item.tsx
index e58188654bd..fc59b229bb6 100644
--- a/web/app/components/workflow/nodes/http/components/key-value/key-value-edit/item.tsx
+++ b/web/app/components/workflow/nodes/http/components/key-value/key-value-edit/item.tsx
@@ -22,7 +22,6 @@ import { useTranslation } from 'react-i18next'
import { VarType } from '@/app/components/workflow/types'
import VarReferencePicker from '../../../../_base/components/variable/var-reference-picker'
import InputItem from './input-item'
-// import Input from '@/app/components/base/input'
const i18nPrefix = 'nodes.http'
diff --git a/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx b/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx
index f0c704111b2..e8c4544f1c5 100644
--- a/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx
+++ b/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx
@@ -5,7 +5,7 @@ import type { CredentialFormSchema } from '@/app/components/header/account-setti
import type { Tool } from '@/app/components/tools/types'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
-import { useState } from 'react'
+import { useId, useState } from 'react'
import { Infotip } from '@/app/components/base/infotip'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
@@ -78,6 +78,7 @@ const ToolFormItem: FC<Props> = ({
providerType = 'tool',
}) => {
const language = useLanguage()
+ const labelId = useId()
const { name, label, type, required, tooltip, input_schema } = schema
const showSchemaButton = type === FormTypeEnum.object || type === FormTypeEnum.array
const showDescription =
@@ -91,7 +92,10 @@ const ToolFormItem: FC<Props> = ({
<div className="space-y-0.5 py-1">
<div>
<div className="flex min-h-6 min-w-0 items-center">
- <div className="min-w-0 system-sm-medium wrap-break-word text-text-secondary">
+ <div
+ id={labelId}
+ className="min-w-0 system-sm-medium wrap-break-word text-text-secondary"
+ >
{label[language] || label.en_US}
</div>
{required && (
@@ -128,6 +132,7 @@ const ToolFormItem: FC<Props> = ({
)}
</div>
<FormInputItem
+ labelId={labelId}
readOnly={readOnly}
nodeId={nodeId}
schema={schema}
diff --git a/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/item.tsx b/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/item.tsx
index 8a5f83ab396..683b8efc14e 100644
--- a/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/item.tsx
+++ b/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/item.tsx
@@ -5,7 +5,7 @@ import type { Event } from '@/app/components/tools/types'
import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'
import type { PluginTriggerVarInputs } from '@/app/components/workflow/nodes/trigger-plugin/types'
import { Button } from '@langgenius/dify-ui/button'
-import { useState } from 'react'
+import { useId, useState } from 'react'
import { Infotip } from '@/app/components/base/infotip'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
@@ -38,6 +38,7 @@ const TriggerFormItem: FC<Props> = ({
disableVariableInsertion = false,
}) => {
const language = useLanguage()
+ const labelId = useId()
const { name, label, type, required, tooltip, input_schema } = schema
const showSchemaButton = type === FormTypeEnum.object || type === FormTypeEnum.array
const showDescription =
@@ -51,7 +52,7 @@ const TriggerFormItem: FC<Props> = ({
<div className="space-y-0.5 py-1">
<div>
<div className="flex h-6 items-center">
- <div className="system-sm-medium text-text-secondary">
+ <div id={labelId} className="system-sm-medium text-text-secondary">
{label[language] || label.en_US}
</div>
{required && (
@@ -88,6 +89,7 @@ const TriggerFormItem: FC<Props> = ({
)}
</div>
<FormInputItem
+ labelId={labelId}
readOnly={readOnly}
nodeId={nodeId}
schema={schema}
diff --git a/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx
index 685bdf3a1b0..cde13c7d47e 100644
--- a/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx
@@ -15,8 +15,6 @@ const {
mockHandleParamsChange,
mockHandleBodyChange,
mockHandleResponseBodyChange,
- mockToastSuccess,
- mockCopy,
mockIsPrivateOrLocalAddress,
} = vi.hoisted(() => ({
mockHandleStatusCodeChange: vi.fn(),
@@ -27,40 +25,9 @@ const {
mockHandleParamsChange: vi.fn(),
mockHandleBodyChange: vi.fn(),
mockHandleResponseBodyChange: vi.fn(),
- mockToastSuccess: vi.fn(),
- mockCopy: vi.fn(),
mockIsPrivateOrLocalAddress: vi.fn((_url: string) => false),
}))
-vi.mock('@langgenius/dify-ui/toast', () => ({
- toast: {
- success: mockToastSuccess,
- },
-}))
-
-vi.mock('copy-to-clipboard', () => ({
- default: mockCopy,
-}))
-
-vi.mock('@/app/components/base/input-with-copy', () => ({
- default: ({
- value,
- placeholder,
- onCopy,
- }: {
- value: string
- placeholder: string
- onCopy: () => void
- }) => (
- <div>
- <input value={value} placeholder={placeholder} readOnly />
- <button data-testid="copy-input" type="button" onClick={onCopy}>
- Copy
- </button>
- </div>
- ),
-}))
-
vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
default: ({ title, children }: { title: string; children: React.ReactNode }) => (
<div>
@@ -241,14 +208,6 @@ describe('WebhookTriggerPanel', () => {
expect(mockGenerateWebhookUrl).not.toHaveBeenCalled()
})
- it('should keep the content type selector aligned with the webhook url row width', () => {
- render(<Panel {...panelProps} />)
-
- const contentTypeTrigger = screen.getAllByRole('combobox')[1]
-
- expect(contentTypeTrigger).toHaveClass('w-full')
- })
-
it('should request a webhook url when the node is writable and missing one', async () => {
mockConfigState.inputs = {
...mockConfigState.inputs,
@@ -287,11 +246,28 @@ describe('WebhookTriggerPanel', () => {
})
describe('Interactions', () => {
- it('should handle method, content type, table, response, and copy actions', async () => {
+ it('copies the labeled readonly webhook URL without editing it', async () => {
+ const user = userEvent.setup()
+ render(<Panel {...panelProps} />)
+ const input = screen.getByRole('textbox', {
+ name: 'workflow.nodes.triggerWebhook.webhookUrl',
+ })
+ expect(input).toHaveAttribute('readonly')
+ await user.click(screen.getByText('workflow.nodes.triggerWebhook.webhookUrl'))
+ expect(input).toHaveFocus()
+ await user.click(
+ screen.getByRole('button', { name: 'appOverview.overview.appInfo.embedded.copy' }),
+ )
+ expect(await navigator.clipboard.readText()).toBe('https://example.com/webhook')
+ expect(
+ await screen.findByRole('button', { name: 'workflow.nodes.triggerWebhook.urlCopied' }),
+ ).toHaveFocus()
+ })
+
+ it('should handle method, content type, table, and response actions', async () => {
const user = userEvent.setup()
render(<Panel {...panelProps} />)
- fireEvent.click(screen.getByTestId('copy-input'))
await user.click(screen.getAllByRole('combobox')[0]!)
await user.click(await screen.findByRole('option', { name: 'GET' }))
await user.click(screen.getAllByRole('combobox')[1]!)
@@ -302,7 +278,6 @@ describe('WebhookTriggerPanel', () => {
fireEvent.change(screen.getByDisplayValue('ok'), { target: { value: 'updated body' } })
fireEvent.click(screen.getByTestId('toggle-output-vars'))
- expect(mockToastSuccess).toHaveBeenCalledWith('workflow.nodes.triggerWebhook.urlCopied')
expect(mockHandleMethodChange).toHaveBeenCalledWith('GET')
expect(mockHandleContentTypeChange).toHaveBeenCalledWith('text/plain')
expect(mockHandleParamsChange).toHaveBeenCalledWith([
@@ -317,8 +292,8 @@ describe('WebhookTriggerPanel', () => {
expect(mockHandleResponseBodyChange).toHaveBeenCalledWith('updated body')
})
- it('should render the debug url card, copy it, and show the private-address warning', () => {
- vi.useFakeTimers()
+ it('copies the debug URL from the keyboard and announces success while keeping its visible name', async () => {
+ const user = userEvent.setup()
mockIsPrivateOrLocalAddress.mockReturnValue(true)
mockConfigState.inputs = {
...mockConfigState.inputs,
@@ -327,15 +302,26 @@ describe('WebhookTriggerPanel', () => {
render(<Panel {...panelProps} />)
- fireEvent.click(screen.getByText('http://127.0.0.1:8000/debug'))
-
- expect(mockCopy).toHaveBeenCalledWith('http://127.0.0.1:8000/debug')
+ const button = screen.getByRole('button', {
+ name: 'workflow.nodes.triggerWebhook.debugUrlTitle http://127.0.0.1:8000/debug workflow.nodes.triggerWebhook.debugUrlCopy',
+ })
+ await user.click(
+ screen.getByRole('textbox', { name: 'workflow.nodes.triggerWebhook.webhookUrl' }),
+ )
+ await user.tab()
+ await user.tab()
+ expect(button).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(await navigator.clipboard.readText()).toBe('http://127.0.0.1:8000/debug')
+ await waitFor(() =>
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'workflow.nodes.triggerWebhook.debugUrlCopied',
+ ),
+ )
+ expect(button).toHaveFocus()
expect(
screen.getByText('workflow.nodes.triggerWebhook.debugUrlPrivateAddressWarning'),
).toBeInTheDocument()
-
- vi.runAllTimers()
- vi.useRealTimers()
})
})
})
diff --git a/web/app/components/workflow/nodes/trigger-webhook/panel.tsx b/web/app/components/workflow/nodes/trigger-webhook/panel.tsx
index c4c0b52bd5a..96f8b3d3971 100644
--- a/web/app/components/workflow/nodes/trigger-webhook/panel.tsx
+++ b/web/app/components/workflow/nodes/trigger-webhook/panel.tsx
@@ -1,6 +1,7 @@
import type { FC } from 'react'
import type { HttpMethod, WebhookTriggerNodeType } from './types'
import type { NodePanelProps } from '@/app/components/workflow/types'
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import {
NumberField,
NumberFieldControls,
@@ -17,14 +18,14 @@ import {
SelectItemText,
SelectLabel,
SelectTrigger,
+ SelectValue,
} from '@langgenius/dify-ui/select'
-import { toast } from '@langgenius/dify-ui/toast'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import copy from 'copy-to-clipboard'
+import { useClipboard } from 'foxact/use-clipboard'
import * as React from 'react'
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import InputWithCopy from '@/app/components/base/input-with-copy'
+import { CopyFeedback } from '@/app/components/base/copy-feedback'
import Field from '@/app/components/workflow/nodes/_base/components/field'
import OutputVars from '@/app/components/workflow/nodes/_base/components/output-vars'
import Split from '@/app/components/workflow/nodes/_base/components/split'
@@ -83,8 +84,8 @@ const WebhookMethodSelector = ({
disabled={disabled}
onValueChange={handleMethodChange}
>
- <SelectTrigger aria-label={label} className="h-8 pr-8 text-sm">
- {selectedMethod?.name}
+ <SelectTrigger aria-label={label}>
+ <SelectValue>{selectedMethod?.name}</SelectValue>
</SelectTrigger>
<SelectContent className="w-26 min-w-26">
{HTTP_METHODS.map((item) => (
@@ -100,7 +101,8 @@ const WebhookMethodSelector = ({
const Panel: FC<NodePanelProps<WebhookTriggerNodeType>> = ({ id, data }) => {
const { t } = useTranslation()
- const [debugUrlCopied, setDebugUrlCopied] = React.useState(false)
+ const webhookUrlId = useId()
+ const { copied: debugUrlCopied, copy: copyDebugUrl } = useClipboard({ timeout: 2000 })
const [outputVarsCollapsed, setOutputVarsCollapsed] = useState(false)
const {
readOnly,
@@ -129,9 +131,18 @@ const Panel: FC<NodePanelProps<WebhookTriggerNodeType>> = ({ id, data }) => {
return (
<div className="mt-2">
+ <span role="status" className="sr-only">
+ {debugUrlCopied ? t(($) => $[`${i18nPrefix}.debugUrlCopied`], { ns: 'workflow' }) : ''}
+ </span>
<div className="space-y-4 px-4 pt-2 pb-3">
{/* Webhook URL Section */}
- <Field title={t(($) => $[`${i18nPrefix}.webhookUrl`], { ns: 'workflow' })}>
+ <Field
+ title={
+ <label htmlFor={webhookUrlId}>
+ {t(($) => $[`${i18nPrefix}.webhookUrl`], { ns: 'workflow' })}
+ </label>
+ }
+ >
<div className="space-y-1">
<div className="flex gap-1" style={{ height: '32px' }}>
<div className="w-26 shrink-0">
@@ -143,18 +154,23 @@ const Panel: FC<NodePanelProps<WebhookTriggerNodeType>> = ({ id, data }) => {
onChange={handleMethodChange}
/>
</div>
- <div className="flex-1" style={{ width: '284px' }}>
- <InputWithCopy
+ <InputGroup className="min-w-0 flex-1">
+ <InputGroupInput
+ id={webhookUrlId}
value={inputs.webhook_url || ''}
placeholder={t(($) => $[`${i18nPrefix}.webhookUrlPlaceholder`], {
ns: 'workflow',
})}
readOnly
- onCopy={() => {
- toast.success(t(($) => $[`${i18nPrefix}.urlCopied`], { ns: 'workflow' }))
- }}
/>
- </div>
+ <InputGroupAddon align="inline-end" className="pe-2">
+ <CopyFeedback
+ content={inputs.webhook_url || ''}
+ copiedLabel={t(($) => $[`${i18nPrefix}.urlCopied`], { ns: 'workflow' })}
+ className="size-4 rounded-sm p-0 [&>span]:size-3.5"
+ />
+ </InputGroupAddon>
+ </InputGroup>
</div>
{inputs.webhook_debug_url && (
<div className="space-y-2">
@@ -163,16 +179,14 @@ const Panel: FC<NodePanelProps<WebhookTriggerNodeType>> = ({ id, data }) => {
render={
<button
type="button"
- aria-label={t(($) => $[`${i18nPrefix}.debugUrlCopy`], { ns: 'workflow' })}
- className="flex cursor-pointer gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors"
+ className="flex cursor-pointer gap-1.5 rounded-lg px-1 py-1.5 text-left outline-hidden transition-colors focus-visible:ring-2 focus-visible:ring-state-accent-solid"
style={{ width: '368px', height: '38px' }}
onClick={() => {
- copy(inputs.webhook_debug_url || '')
- setDebugUrlCopied(true)
- setTimeout(() => setDebugUrlCopied(false), 2000)
+ copyDebugUrl(inputs.webhook_debug_url || '')
}}
>
<span
+ aria-hidden="true"
className="mt-0.5 w-0.5 bg-divider-regular"
style={{ height: '28px' }}
/>
@@ -184,11 +198,15 @@ const Panel: FC<NodePanelProps<WebhookTriggerNodeType>> = ({ id, data }) => {
{inputs.webhook_debug_url}
</span>
</span>
+ <span className="sr-only">
+ {t(($) => $[`${i18nPrefix}.debugUrlCopy`], { ns: 'workflow' })}
+ </span>
</button>
}
/>
<TooltipContent
- placement="top"
+ placement="bottom"
+ sideOffset={4}
className="rounded-md border border-components-panel-border bg-components-tooltip-bg px-1.5 py-1 system-xs-regular text-text-primary shadow-lg backdrop-blur-xs"
>
{debugUrlCopied
@@ -208,29 +226,27 @@ const Panel: FC<NodePanelProps<WebhookTriggerNodeType>> = ({ id, data }) => {
{/* Content Type */}
<Field title={t(($) => $[`${i18nPrefix}.contentType`], { ns: 'workflow' })}>
- <div className="w-full max-w-98">
- <Select
- key={`${id}-content-type-${inputs.content_type}`}
- value={selectedContentType?.value ?? null}
- disabled={readOnly}
- onValueChange={(value) => value && handleContentTypeChange(value)}
- >
- <SelectLabel className="sr-only">
- {t(($) => $[`${i18nPrefix}.contentType`], { ns: 'workflow' })}
- </SelectLabel>
- <SelectTrigger className="h-8 w-full text-sm">
- {selectedContentType?.name}
- </SelectTrigger>
- <SelectContent>
- {CONTENT_TYPES.map((item) => (
- <SelectItem key={item.value} value={item.value}>
- <SelectItemText>{item.name}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
+ <Select
+ key={`${id}-content-type-${inputs.content_type}`}
+ value={selectedContentType?.value ?? null}
+ disabled={readOnly}
+ onValueChange={(value) => value && handleContentTypeChange(value)}
+ >
+ <SelectLabel className="sr-only">
+ {t(($) => $[`${i18nPrefix}.contentType`], { ns: 'workflow' })}
+ </SelectLabel>
+ <SelectTrigger>
+ <SelectValue>{selectedContentType?.name}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {CONTENT_TYPES.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ <SelectItemText>{item.name}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
</Field>
{/* Query Parameters */}
diff --git a/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx b/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx
index 65fdabf5e06..e2e43322165 100644
--- a/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx
@@ -115,7 +115,7 @@ describe('InputsPanel', () => {
)
expect(screen.getByDisplayValue('overridden question')).toHaveFocus()
- expect(screen.getByRole('spinbutton')).toHaveValue(2)
+ expect(screen.getByRole('textbox', { name: 'Count' })).toHaveValue('2')
expect(screen.getByText('common.imageUploader.pasteImageLink')).toBeInTheDocument()
})
})
diff --git a/web/app/components/workflow/panel/env-panel/variable-modal.tsx b/web/app/components/workflow/panel/env-panel/variable-modal.tsx
index 3f0672806cb..ca843b1868e 100644
--- a/web/app/components/workflow/panel/env-panel/variable-modal.tsx
+++ b/web/app/components/workflow/panel/env-panel/variable-modal.tsx
@@ -1,14 +1,17 @@
import type { EnvironmentVariable, EnvironmentVariableValue } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { IconButton } from '@langgenius/dify-ui/icon-button'
+import { Input } from '@langgenius/dify-ui/input'
+import { NumberField, NumberFieldGroup, NumberFieldInput } from '@langgenius/dify-ui/number-field'
+import { Textarea } from '@langgenius/dify-ui/textarea'
import { toast } from '@langgenius/dify-ui/toast'
import * as React from 'react'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { v4 as uuid4 } from 'uuid'
import { Infotip } from '@/app/components/base/infotip'
-import Input from '@/app/components/base/input'
import { isLLMEnvironmentVariableValue } from '@/app/components/workflow/llm-environment-variable'
import { LLMEnvironmentVariableValueField } from '@/app/components/workflow/llm-environment-variable-value-field'
import { useWorkflowStore } from '@/app/components/workflow/store'
@@ -69,7 +72,11 @@ const VariableModal = ({ env, onClose, onSave }: ModalPropsType) => {
}
if (nextType === 'number') {
- if (value === undefined || value === '' || Number.isNaN(Number(value))) setValue('')
+ setValue(
+ value === undefined || value === '' || !Number.isFinite(Number(value))
+ ? undefined
+ : Number(value),
+ )
return
}
@@ -107,7 +114,7 @@ const VariableModal = ({ env, onClose, onSave }: ModalPropsType) => {
id: env ? env.id : uuid4(),
value_type: type,
name,
- value: type === 'number' ? Number(value) : value,
+ value,
description,
})
onClose()
@@ -124,7 +131,11 @@ const VariableModal = ({ env, onClose, onSave }: ModalPropsType) => {
}, [env, workflowStore])
return (
- <div
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ handleSave()
+ }}
className={cn(
'flex h-full w-90 flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-2xl',
)}
@@ -212,78 +223,79 @@ const VariableModal = ({ env, onClose, onSave }: ModalPropsType) => {
</div>
</div>
{/* name */}
- <div className="mb-4">
- <div className="mb-1 flex h-6 items-center system-sm-semibold text-text-secondary">
+ <Field name="name" className="mb-4">
+ <FieldLabel className="system-sm-semibold">
{t(($) => $['env.modal.name'], { ns: 'workflow' })}
- </div>
- <div className="flex">
- <Input
- placeholder={t(($) => $['env.modal.namePlaceholder'], { ns: 'workflow' }) || ''}
- value={name}
- onChange={handleVarNameChange}
- onBlur={(e) => checkVariableName(e.target.value)}
- type="text"
- />
- </div>
- </div>
+ </FieldLabel>
+ <Input
+ placeholder={t(($) => $['env.modal.namePlaceholder'], { ns: 'workflow' }) || ''}
+ value={name}
+ onChange={handleVarNameChange}
+ onBlur={(e) => checkVariableName(e.target.value)}
+ type="text"
+ />
+ </Field>
{/* value */}
- <div className="mb-4">
- <div className="mb-1 flex h-6 items-center system-sm-semibold text-text-secondary">
- {type === 'llm'
- ? t(($) => $['modelProvider.model'], { ns: 'common' })
- : t(($) => $['env.modal.value'], { ns: 'workflow' })}
- </div>
- <div className="flex">
- {type === 'llm' ? (
- <LLMEnvironmentVariableValueField
- value={isLLMEnvironmentVariableValue(value) ? value : undefined}
- requiredMode={originalLLMMode}
- popupClassName="w-[328px]! max-w-[328px]!"
- onChange={setValue}
- />
- ) : type !== 'number' ? (
- <textarea
- className="block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 system-sm-regular text-components-input-text-filled caret-primary-600 outline-hidden placeholder:system-sm-regular placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"
- value={typeof value === 'string' || typeof value === 'number' ? value : ''}
- placeholder={t(($) => $['env.modal.valuePlaceholder'], { ns: 'workflow' }) || ''}
- onChange={(e) => setValue(e.target.value)}
- />
- ) : (
- <Input
- placeholder={t(($) => $['env.modal.valuePlaceholder'], { ns: 'workflow' }) || ''}
- value={typeof value === 'string' || typeof value === 'number' ? value : ''}
- onChange={(e) => setValue(e.target.value)}
- type="number"
- />
- )}
- </div>
- </div>
+ <Field name="value" className="mb-4">
+ {type === 'llm' ? (
+ <div className="py-1 system-sm-semibold text-text-secondary">
+ {t(($) => $['modelProvider.model'], { ns: 'common' })}
+ </div>
+ ) : (
+ <FieldLabel className="system-sm-semibold">
+ {t(($) => $['env.modal.value'], { ns: 'workflow' })}
+ </FieldLabel>
+ )}
+ {type === 'llm' ? (
+ <LLMEnvironmentVariableValueField
+ value={isLLMEnvironmentVariableValue(value) ? value : undefined}
+ requiredMode={originalLLMMode}
+ popupClassName="w-[328px]! max-w-[328px]!"
+ onChange={setValue}
+ />
+ ) : type !== 'number' ? (
+ <Textarea
+ className="h-20 p-2"
+ value={typeof value === 'string' || typeof value === 'number' ? value : ''}
+ placeholder={t(($) => $['env.modal.valuePlaceholder'], { ns: 'workflow' }) || ''}
+ onValueChange={(value) => setValue(value)}
+ />
+ ) : (
+ <NumberField
+ step="any"
+ value={typeof value === 'number' ? value : null}
+ onValueChange={(value) => setValue(value ?? undefined)}
+ >
+ <NumberFieldGroup>
+ <NumberFieldInput
+ placeholder={t(($) => $['env.modal.valuePlaceholder'], { ns: 'workflow' })}
+ />
+ </NumberFieldGroup>
+ </NumberField>
+ )}
+ </Field>
{/* description */}
- <div className="">
- <div className="mb-1 flex h-6 items-center system-sm-semibold text-text-secondary">
+ <Field name="description">
+ <FieldLabel className="system-sm-semibold">
{t(($) => $['env.modal.description'], { ns: 'workflow' })}
- </div>
- <div className="flex">
- <textarea
- className="block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 system-sm-regular text-components-input-text-filled caret-primary-600 outline-hidden placeholder:system-sm-regular placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"
- value={description}
- placeholder={
- t(($) => $['env.modal.descriptionPlaceholder'], { ns: 'workflow' }) || ''
- }
- onChange={(e) => setDescription(e.target.value)}
- />
- </div>
- </div>
+ </FieldLabel>
+ <Textarea
+ className="h-20 p-2"
+ value={description}
+ placeholder={t(($) => $['env.modal.descriptionPlaceholder'], { ns: 'workflow' }) || ''}
+ onValueChange={(value) => setDescription(value)}
+ />
+ </Field>
</div>
<div className="flex flex-row-reverse rounded-b-2xl p-4 pt-2">
<div className="flex gap-2">
<Button onClick={onClose}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
- <Button variant="primary" onClick={handleSave}>
+ <Button variant="primary" type="submit">
{t(($) => $['operation.save'], { ns: 'common' })}
</Button>
</div>
</div>
- </div>
+ </form>
)
}