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): migrate legacy form controls to Dify UI (#41682)

yyh59021616d4c2
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 03c49ef9a02..c91d85911e4 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -102,14 +102,6 @@
"count": 2
}
},
- "web/app/account/(commonLayout)/delete-account/components/verify-email.tsx": {
- "eslint-react/set-state-in-effect": {
- "count": 1
- },
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/app/annotation/add-annotation-modal/edit-item/index.tsx": {
"erasable-syntax-only/enums": {
"count": 1
@@ -3515,9 +3507,6 @@
}
},
"web/app/components/workflow/nodes/_base/components/variable/output-var-list.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"typescript/no-non-null-asserted-optional-chain": {
"count": 1
}
@@ -3987,11 +3976,6 @@
"count": 1
}
},
- "web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-string.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-value-method.tsx": {
"jsx-a11y/click-events-have-key-events": {
"count": 1
@@ -4886,21 +4870,11 @@
"count": 1
}
},
- "web/app/forgot-password/ChangePasswordForm.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/forgot-password/ForgotPasswordForm.spec.tsx": {
"typescript/no-explicit-any": {
"count": 5
}
},
- "web/app/forgot-password/ForgotPasswordForm.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/init/InitPasswordPopup.tsx": {
"typescript/no-explicit-any": {
"count": 1
@@ -4921,11 +4895,6 @@
"count": 1
}
},
- "web/app/signin/one-more-step.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/signup/layout.tsx": {
"typescript/no-explicit-any": {
"count": 1
diff --git a/packages/dify-ui/src/form/index.tsx b/packages/dify-ui/src/form/index.tsx
index 411863561f5..c5e3b07499a 100644
--- a/packages/dify-ui/src/form/index.tsx
+++ b/packages/dify-ui/src/form/index.tsx
@@ -5,8 +5,10 @@ import { Form as BaseForm } from '@base-ui/react/form'
const Form = BaseForm
+type FormActions = BaseFormNS.Actions
+
type FormProps<FormValues extends BaseFormNS.Values = BaseFormNS.Values> =
BaseFormNS.Props<FormValues>
export { Form }
-export type { FormProps }
+export type { FormActions, FormProps }
diff --git a/web/app/account/(commonLayout)/delete-account/components/__tests__/check-email.spec.tsx b/web/app/account/(commonLayout)/delete-account/components/__tests__/check-email.spec.tsx
new file mode 100644
index 00000000000..932bf12af8f
--- /dev/null
+++ b/web/app/account/(commonLayout)/delete-account/components/__tests__/check-email.spec.tsx
@@ -0,0 +1,59 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import CheckEmail from '../check-email'
+
+const mockGetDeleteEmailVerifyCode = vi.fn()
+
+vi.mock('@tanstack/react-query', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()
+ return {
+ ...actual,
+ useSuspenseQuery: ({
+ select,
+ }: {
+ select: (data: { profile: { email: string } }) => string
+ }) => ({
+ data: select({ profile: { email: '[email protected]' } }),
+ }),
+ }
+})
+
+vi.mock('../../state', () => ({
+ useSendDeleteAccountEmail: () => ({
+ isPending: false,
+ mutateAsync: mockGetDeleteEmailVerifyCode,
+ }),
+}))
+
+describe('CheckEmail', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetDeleteEmailVerifyCode.mockResolvedValue({ result: 'success' })
+ })
+
+ it('submits with Enter only after the account email matches', async () => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+
+ render(<CheckEmail onCancel={vi.fn()} onConfirm={onConfirm} />)
+
+ const input = screen.getByRole('textbox', { name: 'common.account.deleteLabel' })
+ const submitButton = screen.getByRole('button', {
+ name: 'common.account.sendVerificationButton',
+ })
+
+ await user.type(input, '[email protected]{Enter}')
+
+ expect(submitButton).toBeDisabled()
+ expect(mockGetDeleteEmailVerifyCode).not.toHaveBeenCalled()
+
+ await user.clear(input)
+ await user.type(input, '[email protected]{Enter}')
+
+ await waitFor(() => {
+ expect(mockGetDeleteEmailVerifyCode).toHaveBeenCalledOnce()
+ })
+ expect(submitButton).toBeEnabled()
+ expect(onConfirm).toHaveBeenCalledOnce()
+ })
+})
diff --git a/web/app/account/(commonLayout)/delete-account/components/__tests__/feed-back.spec.tsx b/web/app/account/(commonLayout)/delete-account/components/__tests__/feed-back.spec.tsx
new file mode 100644
index 00000000000..6ee1deb284a
--- /dev/null
+++ b/web/app/account/(commonLayout)/delete-account/components/__tests__/feed-back.spec.tsx
@@ -0,0 +1,69 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import FeedBack from '../feed-back'
+
+const mockPush = vi.fn()
+const mockSendFeedback = vi.fn()
+const mockLogout = vi.fn()
+
+vi.mock('@tanstack/react-query', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()
+ return {
+ ...actual,
+ useSuspenseQuery: ({
+ select,
+ }: {
+ select: (data: { profile: { email: string } }) => string
+ }) => ({
+ data: select({ profile: { email: '[email protected]' } }),
+ }),
+ }
+})
+
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({ push: mockPush }),
+}))
+
+vi.mock('@/service/use-common', () => ({
+ useLogout: () => ({ mutateAsync: mockLogout }),
+}))
+
+vi.mock('@langgenius/dify-ui/toast', () => ({
+ toast: { info: vi.fn() },
+}))
+
+vi.mock('../../state', () => ({
+ useDeleteAccountFeedback: () => ({
+ isPending: false,
+ mutateAsync: mockSendFeedback,
+ }),
+}))
+
+describe('FeedBack', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockSendFeedback.mockResolvedValue(undefined)
+ mockLogout.mockResolvedValue(undefined)
+ })
+
+ it('labels and submits the optional feedback field through the form', async () => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+
+ render(<FeedBack onCancel={vi.fn()} onConfirm={onConfirm} />)
+
+ const feedback = screen.getByRole('textbox', { name: 'common.account.feedbackLabel' })
+ await user.type(feedback, 'The workspace is no longer needed.')
+ await user.click(screen.getByRole('button', { name: 'common.operation.submit' }))
+
+ await waitFor(() => {
+ expect(mockSendFeedback).toHaveBeenCalledWith({
+ email: '[email protected]',
+ feedback: 'The workspace is no longer needed.',
+ })
+ })
+ expect(onConfirm).toHaveBeenCalledOnce()
+ expect(mockLogout).toHaveBeenCalledOnce()
+ expect(mockPush).toHaveBeenCalledWith('/signin')
+ })
+})
diff --git a/web/app/account/(commonLayout)/delete-account/components/__tests__/verify-email.spec.tsx b/web/app/account/(commonLayout)/delete-account/components/__tests__/verify-email.spec.tsx
new file mode 100644
index 00000000000..1602a02bbb5
--- /dev/null
+++ b/web/app/account/(commonLayout)/delete-account/components/__tests__/verify-email.spec.tsx
@@ -0,0 +1,62 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import VerifyEmail from '../verify-email'
+
+const mockConfirmDeleteAccount = vi.fn()
+const mockSendEmail = vi.fn()
+
+vi.mock('../../state', () => ({
+ useAccountDeleteStore: (selector: (state: { sendEmailToken: string }) => string) =>
+ selector({ sendEmailToken: 'email-token' }),
+ useConfirmDeleteAccount: () => ({
+ isPending: false,
+ mutateAsync: mockConfirmDeleteAccount,
+ }),
+ useSendDeleteAccountEmail: () => ({ mutate: mockSendEmail }),
+}))
+
+vi.mock('@/app/components/signin/countdown', () => ({
+ default: () => null,
+}))
+
+describe('VerifyEmail', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockConfirmDeleteAccount.mockResolvedValue({ result: 'success' })
+ })
+
+ it('submits a complete verification code through the form', async () => {
+ const user = userEvent.setup()
+ const onConfirm = vi.fn()
+
+ render(<VerifyEmail onCancel={vi.fn()} onConfirm={onConfirm} />)
+
+ const input = screen.getByLabelText('common.account.verificationLabel')
+ const submitButton = screen.getByRole('button', {
+ name: 'common.account.permanentlyDeleteButton',
+ })
+
+ expect(submitButton).toBeEnabled()
+ await user.click(submitButton)
+
+ const errors = await screen.findAllByText('common.account.verificationPlaceholder')
+ expect(errors).toHaveLength(1)
+ expect(input).toHaveAttribute('aria-invalid', 'true')
+ expect(input).toHaveAccessibleDescription('common.account.verificationPlaceholder')
+ expect(input).toHaveFocus()
+ expect(mockConfirmDeleteAccount).not.toHaveBeenCalled()
+
+ await user.type(input, '123456')
+
+ expect(submitButton).toBeEnabled()
+ await user.keyboard('{Enter}')
+
+ await waitFor(() => {
+ expect(mockConfirmDeleteAccount).toHaveBeenCalledWith({
+ code: '123456',
+ token: 'email-token',
+ })
+ })
+ expect(onConfirm).toHaveBeenCalledOnce()
+ })
+})
diff --git a/web/app/account/(commonLayout)/delete-account/components/check-email.tsx b/web/app/account/(commonLayout)/delete-account/components/check-email.tsx
index fb555d32f79..fd1b0fe20a7 100644
--- a/web/app/account/(commonLayout)/delete-account/components/check-email.tsx
+++ b/web/app/account/(commonLayout)/delete-account/components/check-email.tsx
@@ -1,5 +1,7 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
+import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useState } from 'react'
@@ -25,16 +27,22 @@ export default function CheckEmail(props: DeleteAccountProps) {
useSendDeleteAccountEmail()
const handleConfirm = useCallback(async () => {
+ if (isSendingEmail || userInputEmail !== userProfileEmail) return
+
try {
const ret = await getDeleteEmailVerifyCode()
if (ret.result === 'success') props.onConfirm()
} catch (error) {
console.error(error)
}
- }, [getDeleteEmailVerifyCode, props])
+ }, [getDeleteEmailVerifyCode, isSendingEmail, props, userInputEmail, userProfileEmail])
return (
- <>
+ <Form
+ onFormSubmit={() => {
+ void handleConfirm()
+ }}
+ >
<div className="py-1 body-md-medium text-text-destructive">
{t(($) => $['account.deleteTip'], { ns: 'common' })}
</div>
@@ -44,33 +52,30 @@ export default function CheckEmail(props: DeleteAccountProps) {
{t(($) => $['account.deletePrivacyLink'], { ns: 'common' })}
</Link>
</div>
- <label
- htmlFor="delete-account-email"
- className="mt-3 mb-1 flex h-6 items-center system-sm-semibold text-text-secondary"
- >
- {t(($) => $['account.deleteLabel'], { ns: 'common' })}
- </label>
- <Input
- id="delete-account-email"
- placeholder={t(($) => $['account.deletePlaceholder'], { ns: 'common' }) as string}
- onChange={(e) => {
- setUserInputEmail(e.target.value)
- }}
- />
+ <Field name="email" className="mt-3">
+ <FieldLabel className="system-sm-semibold">
+ {t(($) => $['account.deleteLabel'], { ns: 'common' })}
+ </FieldLabel>
+ <Input
+ placeholder={t(($) => $['account.deletePlaceholder'], { ns: 'common' }) as string}
+ value={userInputEmail}
+ onValueChange={setUserInputEmail}
+ />
+ </Field>
<div className="mt-3 flex w-full flex-col gap-2">
<Button
+ type="submit"
className="w-full"
- disabled={userInputEmail !== userProfileEmail || isSendingEmail}
+ disabled={userInputEmail !== userProfileEmail}
loading={isSendingEmail}
variant="primary"
- onClick={handleConfirm}
>
{t(($) => $['account.sendVerificationButton'], { ns: 'common' })}
</Button>
- <Button className="w-full" onClick={props.onCancel}>
+ <Button type="button" className="w-full" onClick={props.onCancel}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
</div>
- </>
+ </Form>
)
}
diff --git a/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx b/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx
index 12bcaa1dd36..8b40a65adec 100644
--- a/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx
+++ b/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx
@@ -1,10 +1,12 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { toast } from '@langgenius/dify-ui/toast'
import { useSuspenseQuery } from '@tanstack/react-query'
-import { useCallback, useState } from 'react'
+import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { useRouter } from '@/next/navigation'
@@ -16,6 +18,10 @@ type DeleteAccountProps = {
onConfirm: () => void
}
+type FeedbackFormValues = {
+ feedback: string
+}
+
export default function FeedBack(props: DeleteAccountProps) {
const { t } = useTranslation()
const { data: userProfileEmail } = useSuspenseQuery({
@@ -23,7 +29,6 @@ export default function FeedBack(props: DeleteAccountProps) {
select: (data) => data.profile.email,
})
const router = useRouter()
- const [userFeedback, setUserFeedback] = useState('')
const { isPending, mutateAsync: sendFeedback } = useDeleteAccountFeedback()
const { mutateAsync: logout } = useLogout()
@@ -36,17 +41,20 @@ export default function FeedBack(props: DeleteAccountProps) {
} catch (error) {
console.error(error)
}
- }, [router, t])
+ }, [logout, router, t])
- const handleSubmit = useCallback(async () => {
- try {
- await sendFeedback({ feedback: userFeedback, email: userProfileEmail })
- props.onConfirm()
- await handleSuccess()
- } catch (error) {
- console.error(error)
- }
- }, [handleSuccess, userFeedback, sendFeedback, userProfileEmail, props])
+ const handleSubmit = useCallback(
+ async (feedback: string) => {
+ try {
+ await sendFeedback({ feedback, email: userProfileEmail })
+ props.onConfirm()
+ await handleSuccess()
+ } catch (error) {
+ console.error(error)
+ }
+ },
+ [handleSuccess, sendFeedback, userProfileEmail, props],
+ )
const handleSkip = useCallback(() => {
props.onCancel()
@@ -66,26 +74,29 @@ export default function FeedBack(props: DeleteAccountProps) {
<DialogTitle className="pr-8 pb-3 title-2xl-semi-bold text-text-primary">
{t(($) => $['account.feedbackTitle'], { ns: 'common' })}
</DialogTitle>
- <label className="mt-3 mb-1 flex items-center system-sm-semibold text-text-secondary">
- {t(($) => $['account.feedbackLabel'], { ns: 'common' })}
- </label>
- <Textarea
- aria-label={t(($) => $['account.feedbackLabel'], { ns: 'common' }) as string}
- rows={6}
- value={userFeedback}
- placeholder={t(($) => $['account.feedbackPlaceholder'], { ns: 'common' }) as string}
- onValueChange={(value) => {
- setUserFeedback(value)
+ <Form<FeedbackFormValues>
+ onFormSubmit={({ feedback }) => {
+ void handleSubmit(feedback)
}}
- />
- <div className="mt-3 flex w-full flex-col gap-2">
- <Button className="w-full" loading={isPending} variant="primary" onClick={handleSubmit}>
- {t(($) => $['operation.submit'], { ns: 'common' })}
- </Button>
- <Button className="w-full" onClick={handleSkip}>
- {t(($) => $['operation.skip'], { ns: 'common' })}
- </Button>
- </div>
+ >
+ <Field name="feedback" className="mt-3">
+ <FieldLabel className="py-0 system-sm-semibold">
+ {t(($) => $['account.feedbackLabel'], { ns: 'common' })}
+ </FieldLabel>
+ <Textarea
+ rows={6}
+ placeholder={t(($) => $['account.feedbackPlaceholder'], { ns: 'common' }) as string}
+ />
+ </Field>
+ <div className="mt-3 flex w-full flex-col gap-2">
+ <Button type="submit" className="w-full" loading={isPending} variant="primary">
+ {t(($) => $['operation.submit'], { ns: 'common' })}
+ </Button>
+ <Button type="button" className="w-full" onClick={handleSkip}>
+ {t(($) => $['operation.skip'], { ns: 'common' })}
+ </Button>
+ </div>
+ </Form>
</DialogContent>
</Dialog>
)
diff --git a/web/app/account/(commonLayout)/delete-account/components/verify-email.tsx b/web/app/account/(commonLayout)/delete-account/components/verify-email.tsx
index c5d152aaeff..b0a0eef297b 100644
--- a/web/app/account/(commonLayout)/delete-account/components/verify-email.tsx
+++ b/web/app/account/(commonLayout)/delete-account/components/verify-email.tsx
@@ -1,41 +1,48 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
-import { useCallback, useEffect, useState } from 'react'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
+import { Input } from '@langgenius/dify-ui/input'
+import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
-import Input from '@/app/components/base/input'
import Countdown from '@/app/components/signin/countdown'
import Link from '@/next/link'
import { useAccountDeleteStore, useConfirmDeleteAccount, useSendDeleteAccountEmail } from '../state'
-const CODE_EXP = /[A-Z\d]{6}/gi
-
type DeleteAccountProps = {
onCancel: () => void
onConfirm: () => void
}
+type VerifyEmailFormValues = {
+ verificationCode: string
+}
+
export default function VerifyEmail(props: DeleteAccountProps) {
const { t } = useTranslation()
const emailToken = useAccountDeleteStore((state) => state.sendEmailToken)
- const [verificationCode, setVerificationCode] = useState<string>()
- const [shouldButtonDisabled, setShouldButtonDisabled] = useState(true)
const { mutate: sendEmail } = useSendDeleteAccountEmail()
const { isPending: isDeleting, mutateAsync: confirmDeleteAccount } = useConfirmDeleteAccount()
- useEffect(() => {
- setShouldButtonDisabled(!(verificationCode && CODE_EXP.test(verificationCode)) || isDeleting)
- }, [verificationCode, isDeleting])
+ const handleConfirm = useCallback(
+ async (verificationCode: string) => {
+ if (isDeleting) return
- const handleConfirm = useCallback(async () => {
- try {
- const ret = await confirmDeleteAccount({ code: verificationCode!, token: emailToken })
- if (ret.result === 'success') props.onConfirm()
- } catch (error) {
- console.error(error)
- }
- }, [emailToken, verificationCode, confirmDeleteAccount, props])
+ try {
+ const ret = await confirmDeleteAccount({ code: verificationCode, token: emailToken })
+ if (ret.result === 'success') props.onConfirm()
+ } catch (error) {
+ console.error(error)
+ }
+ },
+ [emailToken, confirmDeleteAccount, isDeleting, props],
+ )
return (
- <>
+ <Form<VerifyEmailFormValues>
+ onFormSubmit={({ verificationCode }) => {
+ void handleConfirm(verificationCode)
+ }}
+ >
<div className="pt-1 body-md-medium text-text-destructive">
{t(($) => $['account.deleteTip'], { ns: 'common' })}
</div>
@@ -45,25 +52,33 @@ export default function VerifyEmail(props: DeleteAccountProps) {
{t(($) => $['account.deletePrivacyLink'], { ns: 'common' })}
</Link>
</div>
- <label className="mt-3 mb-1 flex h-6 items-center system-sm-semibold text-text-secondary">
- {t(($) => $['account.verificationLabel'], { ns: 'common' })}
- </label>
- <Input
- minLength={6}
- maxLength={6}
- placeholder={t(($) => $['account.verificationPlaceholder'], { ns: 'common' }) as string}
- onChange={(e) => {
- setVerificationCode(e.target.value)
- }}
- />
+ <Field name="verificationCode" className="mt-3">
+ <FieldLabel className="system-sm-semibold">
+ {t(($) => $['account.verificationLabel'], { ns: 'common' })}
+ </FieldLabel>
+ <Input
+ autoComplete="one-time-code"
+ inputMode="numeric"
+ required
+ pattern="[0-9]{6}"
+ minLength={6}
+ maxLength={6}
+ placeholder={t(($) => $['account.verificationPlaceholder'], { ns: 'common' }) as string}
+ />
+ <FieldError match="valueMissing">
+ {t(($) => $['account.verificationPlaceholder'], { ns: 'common' })}
+ </FieldError>
+ <FieldError match="patternMismatch">
+ {t(($) => $['account.verificationPlaceholder'], { ns: 'common' })}
+ </FieldError>
+ </Field>
<div className="mt-3 flex w-full flex-col gap-2">
<Button
+ type="submit"
className="w-full"
- disabled={shouldButtonDisabled}
loading={isDeleting}
variant="primary"
tone="destructive"
- onClick={handleConfirm}
>
{t(($) => $['account.permanentlyDeleteButton'], { ns: 'common' })}
</Button>
@@ -72,6 +87,6 @@ export default function VerifyEmail(props: DeleteAccountProps) {
</Button>
<Countdown onResend={sendEmail} />
</div>
- </>
+ </Form>
)
}
diff --git a/web/app/components/base/form/utils/__tests__/zod-submit-validator.spec.ts b/web/app/components/base/form/utils/__tests__/zod-submit-validator.spec.ts
deleted file mode 100644
index 6ab082b9c99..00000000000
--- a/web/app/components/base/form/utils/__tests__/zod-submit-validator.spec.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import * as z from 'zod'
-import { zodSubmitValidator } from '../zod-submit-validator'
-
-describe('zodSubmitValidator', () => {
- it('should return undefined for valid values', () => {
- const validator = zodSubmitValidator(
- z.object({
- name: z.string().min(2),
- }),
- )
-
- expect(validator({ value: { name: 'Alice' } })).toBeUndefined()
- })
-
- it('should return first error message per field for invalid values', () => {
- const validator = zodSubmitValidator(
- z.object({
- name: z.string().min(3, 'Name too short'),
- age: z.number().min(18, 'Must be adult'),
- }),
- )
-
- expect(validator({ value: { name: 'Al', age: 15 } })).toEqual({
- fields: {
- name: 'Name too short',
- age: 'Must be adult',
- },
- })
- })
-
- it('should only keep the first error when multiple errors occur for the same field', () => {
- // Both string() empty check and email() validation will fail here conceptually,
- // but Zod aborts early on type errors sometimes. Let's use custom refinements that both trigger
- const schema = z.object({
- email: z.string().superRefine((val, ctx) => {
- if (!val.includes('@')) {
- ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid email format' })
- }
- if (val.length < 10) {
- ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Email too short' })
- }
- }),
- })
- const validator = zodSubmitValidator(schema)
- // "bad" triggers both missing '@' and length < 10
- expect(validator({ value: { email: 'bad' } })).toEqual({
- fields: {
- email: 'Invalid email format',
- },
- })
- })
-
- it('should ignore root-level issues without a field path', () => {
- const schema = z.object({ value: z.number() }).superRefine((_value, ctx) => {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: 'Root error',
- path: [],
- })
- })
- const validator = zodSubmitValidator(schema)
-
- expect(validator({ value: { value: 1 } })).toEqual({ fields: {} })
- })
-})
diff --git a/web/app/components/base/form/utils/zod-submit-validator.ts b/web/app/components/base/form/utils/zod-submit-validator.ts
deleted file mode 100644
index 247702e838a..00000000000
--- a/web/app/components/base/form/utils/zod-submit-validator.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import type { ZodSchema } from 'zod'
-
-type SubmitValidator<T> = ({
- value,
-}: {
- value: T
-}) => { fields: Record<string, string> } | undefined
-
-export const zodSubmitValidator = <T>(schema: ZodSchema<T>): SubmitValidator<T> => {
- return ({ value }) => {
- const result = schema.safeParse(value)
- if (!result.success) {
- const fieldErrors: Record<string, string> = {}
- for (const issue of result.error.issues) {
- const path = issue.path[0]
- if (path === undefined) continue
- const key = String(path)
- if (!fieldErrors[key]) fieldErrors[key] = issue.message
- }
- return { fields: fieldErrors }
- }
- return undefined
- }
-}
diff --git a/web/app/components/workflow/nodes/_base/components/variable/output-var-list.tsx b/web/app/components/workflow/nodes/_base/components/variable/output-var-list.tsx
index 71f260082e5..884511d6c22 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/output-var-list.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/output-var-list.tsx
@@ -2,13 +2,13 @@
import type { FC } from 'react'
import type { OutputVar } from '../../../code/types'
import type { VarType } from '@/app/components/workflow/types'
+import { Input } from '@langgenius/dify-ui/input'
import { toast } from '@langgenius/dify-ui/toast'
import { useDebounceFn } from 'ahooks'
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 { checkKeys, replaceSpaceWithUnderscoreInVarNameInput } from '@/utils/var'
import RemoveButton from '../remove-button'
import VarTypePicker from './var-type-picker'
@@ -104,17 +104,16 @@ const OutputVarList: FC<Props> = ({ readonly, outputs, outputKeyOrders, onChange
readOnly={readonly}
value={item.variable}
onChange={handleVarNameChange(index)}
- wrapperClassName="grow"
+ aria-label={t(($) => $['common.variableNamePlaceholder'], { ns: 'workflow' })}
+ placeholder={t(($) => $['common.variableNamePlaceholder'], { ns: 'workflow' })}
+ className="grow"
/>
<VarTypePicker
readonly={readonly}
value={item.variable_type}
onChange={handleVarTypeChange(index)}
/>
- <RemoveButton
- className="bg-gray-100! p-2! hover:bg-gray-200!"
- onClick={handleVarRemove(index)}
- />
+ <RemoveButton onClick={handleVarRemove(index)} />
</div>
))}
</div>
diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-string.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-string.tsx
index e4c9f62ae72..94d032f96b8 100644
--- a/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-string.tsx
+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-string.tsx
@@ -1,8 +1,8 @@
import type { ConditionValueMethodProps } from './condition-value-method'
import type { Node, NodeOutPutVar, ValueSelector } from '@/app/components/workflow/types'
+import { Input } from '@langgenius/dify-ui/input'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
-import Input from '@/app/components/base/input'
import { VarType } from '@/app/components/workflow/types'
import ConditionCommonVariableSelector from './condition-common-variable-selector'
import ConditionValueMethod from './condition-value-method'
@@ -64,9 +64,12 @@ const ConditionString = ({
)}
{valueMethod === 'constant' && (
<Input
- className="border-none bg-transparent outline-hidden hover:bg-transparent focus:bg-transparent focus:shadow-none"
+ className="border-none bg-transparent hover:bg-transparent focus:bg-transparent focus:shadow-none focus-visible:ring-2 focus-visible:ring-state-accent-solid"
value={value}
- onChange={(e) => onChange(e.target.value)}
+ onValueChange={onChange}
+ aria-label={t(($) => $['nodes.knowledgeRetrieval.metadata.panel.placeholder'], {
+ ns: 'workflow',
+ })}
placeholder={t(($) => $['nodes.knowledgeRetrieval.metadata.panel.placeholder'], {
ns: 'workflow',
})}
diff --git a/web/app/forgot-password/ChangePasswordForm.spec.tsx b/web/app/forgot-password/ChangePasswordForm.spec.tsx
index f3d054e72fd..dd5fbfdf98b 100644
--- a/web/app/forgot-password/ChangePasswordForm.spec.tsx
+++ b/web/app/forgot-password/ChangePasswordForm.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 useDocumentTitle from '@/hooks/use-document-title'
import { changePasswordWithToken } from '@/service/common'
import { useVerifyForgotPasswordToken } from '@/service/use-common'
@@ -65,17 +66,16 @@ describe('ChangePasswordForm', () => {
})
it('submits with T2 (from validity response), NOT T1 (from URL)', async () => {
+ const user = userEvent.setup()
mockChangePassword.mockResolvedValue({ result: 'success' })
render(<ChangePasswordForm />)
- const inputs = Array.from(
- document.querySelectorAll<HTMLInputElement>('input[type="password"]'),
- ) as [HTMLInputElement, HTMLInputElement]
- fireEvent.change(inputs[0], { target: { value: VALID_PASSWORD } })
- fireEvent.change(inputs[1], { target: { value: VALID_PASSWORD } })
-
- fireEvent.click(screen.getByRole('button', { name: /common\.operation\.reset/ }))
+ const passwordInput = screen.getByLabelText('common.account.newPassword')
+ const confirmPasswordInput = screen.getByLabelText('common.account.confirmPassword')
+ await user.type(passwordInput, VALID_PASSWORD)
+ await user.type(confirmPasswordInput, VALID_PASSWORD)
+ await user.keyboard('{Enter}')
await waitFor(() => {
expect(mockChangePassword).toHaveBeenCalledWith({
@@ -90,22 +90,103 @@ describe('ChangePasswordForm', () => {
})
it('uses the success title after the password is changed', async () => {
+ const user = userEvent.setup()
mockChangePassword.mockResolvedValue({ result: 'success' })
render(<ChangePasswordForm />)
- const inputs = Array.from(
- document.querySelectorAll<HTMLInputElement>('input[type="password"]'),
- ) as [HTMLInputElement, HTMLInputElement]
- fireEvent.change(inputs[0], { target: { value: VALID_PASSWORD } })
- fireEvent.change(inputs[1], { target: { value: VALID_PASSWORD } })
- fireEvent.click(screen.getByRole('button', { name: /common\.operation\.reset/ }))
+ await user.type(screen.getByLabelText('common.account.newPassword'), VALID_PASSWORD)
+ await user.type(screen.getByLabelText('common.account.confirmPassword'), VALID_PASSWORD)
+ await user.click(screen.getByRole('button', { name: /common\.operation\.reset/ }))
expect(
await screen.findByRole('heading', { level: 1, name: 'login.passwordChangedTip' }),
).toBeInTheDocument()
expect(mockUseDocumentTitle).toHaveBeenLastCalledWith('login.passwordChangedTip')
})
+
+ it('keeps one associated error when an invalid password is cleared', async () => {
+ const user = userEvent.setup()
+ render(<ChangePasswordForm />)
+
+ const passwordInput = screen.getByLabelText('common.account.newPassword')
+ expect(passwordInput).toHaveAccessibleDescription('login.error.passwordInvalid')
+
+ await user.type(passwordInput, 'weak')
+ await user.click(screen.getByRole('button', { name: /common\.operation\.reset/ }))
+
+ const invalidErrors = await screen.findAllByText('login.error.passwordInvalid')
+ expect(invalidErrors).toHaveLength(1)
+ expect(passwordInput).toHaveAttribute('aria-invalid', 'true')
+ expect(passwordInput).toHaveAccessibleDescription('login.error.passwordInvalid')
+ expect(passwordInput).toHaveFocus()
+ expect(mockChangePassword).not.toHaveBeenCalled()
+
+ await user.clear(passwordInput)
+ await user.click(screen.getByRole('button', { name: /common\.operation\.reset/ }))
+
+ const emptyErrors = await screen.findAllByText('login.error.passwordEmpty')
+ expect(emptyErrors).toHaveLength(1)
+ expect(screen.queryByText('login.error.passwordInvalid')).not.toBeInTheDocument()
+ expect(passwordInput).toHaveAttribute('aria-invalid', 'true')
+ expect(passwordInput).toHaveAccessibleDescription('login.error.passwordEmpty')
+ expect(passwordInput).toHaveFocus()
+ expect(mockChangePassword).not.toHaveBeenCalled()
+ })
+
+ it('revalidates the confirmation field when the password changes', async () => {
+ const user = userEvent.setup()
+ render(<ChangePasswordForm />)
+
+ const passwordInput = screen.getByLabelText('common.account.newPassword')
+ await user.type(passwordInput, VALID_PASSWORD)
+ const confirmPasswordInput = screen.getByLabelText('common.account.confirmPassword')
+ await user.type(confirmPasswordInput, 'DifferentPass123!{Enter}')
+
+ const error = await screen.findByText('common.account.notEqual')
+ expect(confirmPasswordInput).toHaveAttribute('aria-invalid', 'true')
+ expect(confirmPasswordInput).toHaveAccessibleDescription(error.textContent ?? '')
+ expect(confirmPasswordInput).toHaveFocus()
+ expect(mockChangePassword).not.toHaveBeenCalled()
+
+ await user.clear(passwordInput)
+ await user.type(passwordInput, 'DifferentPass123!')
+
+ await waitFor(() => {
+ expect(screen.queryByText('common.account.notEqual')).not.toBeInTheDocument()
+ })
+ expect(confirmPasswordInput).not.toHaveAttribute('aria-invalid', 'true')
+ expect(mockChangePassword).not.toHaveBeenCalled()
+ })
+
+ it('prevents duplicate submissions while the password is changing', async () => {
+ const user = userEvent.setup()
+ let resolveRequest:
+ | ((value: Awaited<ReturnType<typeof changePasswordWithToken>>) => void)
+ | undefined
+ mockChangePassword.mockReturnValue(
+ new Promise((resolve) => {
+ resolveRequest = resolve
+ }),
+ )
+
+ render(<ChangePasswordForm />)
+
+ await user.type(screen.getByLabelText('common.account.newPassword'), VALID_PASSWORD)
+ await user.type(screen.getByLabelText('common.account.confirmPassword'), VALID_PASSWORD)
+
+ const submitButton = screen.getByRole('button', { name: /common\.operation\.reset/ })
+ await user.click(submitButton)
+
+ await waitFor(() => {
+ expect(submitButton).toHaveAttribute('aria-disabled', 'true')
+ })
+ await user.click(submitButton)
+ expect(mockChangePassword).toHaveBeenCalledTimes(1)
+
+ resolveRequest?.({ result: 'success' })
+ await screen.findByRole('heading', { level: 1, name: 'login.passwordChangedTip' })
+ })
})
describe('when token is invalid', () => {
diff --git a/web/app/forgot-password/ChangePasswordForm.tsx b/web/app/forgot-password/ChangePasswordForm.tsx
index dc35ce3c8be..dff1204a09f 100644
--- a/web/app/forgot-password/ChangePasswordForm.tsx
+++ b/web/app/forgot-password/ChangePasswordForm.tsx
@@ -1,9 +1,17 @@
'use client'
-import { CheckCircleIcon } from '@heroicons/react/24/solid'
+import type { FormActions } from '@langgenius/dify-ui/form'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { toast } from '@langgenius/dify-ui/toast'
-import { useCallback, useState } from 'react'
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FieldValidity,
+} from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
+import { Input } from '@langgenius/dify-ui/input'
+import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import { validPassword } from '@/config'
@@ -12,7 +20,11 @@ import { useSearchParams } from '@/next/navigation'
import { changePasswordWithToken } from '@/service/common'
import { useVerifyForgotPasswordToken } from '@/service/use-common'
import { basePath } from '@/utils/var'
-import Input from '../components/base/input'
+
+type PasswordFormValues = {
+ password: string
+ confirmPassword: string
+}
const ChangePasswordForm = () => {
const { t } = useTranslation()
@@ -22,8 +34,9 @@ const ChangePasswordForm = () => {
const { data: verifyTokenRes, refetch: revalidateToken } = useVerifyForgotPasswordToken(token)
- const [password, setPassword] = useState('')
- const [confirmPassword, setConfirmPassword] = useState('')
+ const formActionsRef = useRef<FormActions>(null)
+ const confirmPasswordRef = useRef<HTMLInputElement>(null)
+ const [isSubmitting, setIsSubmitting] = useState(false)
const [showSuccess, setShowSuccess] = useState(false)
const isVerifyingToken = !isTokenMissing && !verifyTokenRes
const isTokenInvalid = isTokenMissing || (verifyTokenRes && !verifyTokenRes.is_valid)
@@ -36,44 +49,30 @@ const ChangePasswordForm = () => {
: t(($) => $.changePassword, { ns: 'login' })
useDocumentTitle(documentTitle)
- const showErrorMessage = useCallback((message: string) => {
- toast.error(message)
- }, [])
-
- const valid = useCallback(() => {
- if (!password.trim()) {
- showErrorMessage(t(($) => $['error.passwordEmpty'], { ns: 'login' }))
- return false
- }
- if (!validPassword.test(password)) {
- showErrorMessage(t(($) => $['error.passwordInvalid'], { ns: 'login' }))
- return false
- }
- if (password !== confirmPassword) {
- showErrorMessage(t(($) => $['account.notEqual'], { ns: 'common' }))
- return false
- }
- return true
- }, [password, confirmPassword, showErrorMessage, t])
-
- const handleChangePassword = useCallback(async () => {
- const resetToken = verifyTokenRes?.token ?? ''
+ const handleChangePassword = useCallback(
+ async (formValues: PasswordFormValues) => {
+ if (isSubmitting) return
+ const resetToken = verifyTokenRes?.token ?? ''
- if (!valid()) return
- try {
- await changePasswordWithToken({
- url: '/forgot-password/resets',
- body: {
- token: resetToken,
- new_password: password,
- password_confirm: confirmPassword,
- },
- })
- setShowSuccess(true)
- } catch {
- await revalidateToken()
- }
- }, [confirmPassword, password, revalidateToken, verifyTokenRes?.token, valid])
+ setIsSubmitting(true)
+ try {
+ await changePasswordWithToken({
+ url: '/forgot-password/resets',
+ body: {
+ token: resetToken,
+ new_password: formValues.password,
+ password_confirm: formValues.confirmPassword,
+ },
+ })
+ setShowSuccess(true)
+ } catch {
+ await revalidateToken()
+ } finally {
+ setIsSubmitting(false)
+ }
+ },
+ [isSubmitting, revalidateToken, verifyTokenRes?.token],
+ )
return (
<div
@@ -112,54 +111,90 @@ const ChangePasswordForm = () => {
</div>
<div className="mx-auto mt-6 w-full">
- <div className="relative">
- {/* Password */}
- <div className="mb-5">
- <label
- htmlFor="password"
- className="my-2 flex items-center justify-between text-sm font-medium text-text-primary"
- >
- {t(($) => $['account.newPassword'], { ns: 'common' })}
- </label>
+ <Form<PasswordFormValues>
+ actionsRef={formActionsRef}
+ className="relative"
+ onFormSubmit={(formValues) => {
+ void handleChangePassword(formValues)
+ }}
+ >
+ <Field
+ name="password"
+ validate={(value) => {
+ const passwordValue = String(value)
+ if (!passwordValue.trim())
+ return t(($) => $['error.passwordEmpty'], { ns: 'login' })
+ return validPassword.test(passwordValue)
+ ? null
+ : t(($) => $['error.passwordInvalid'], { ns: 'login' })
+ }}
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $['account.newPassword'], { ns: 'common' })}</FieldLabel>
<Input
- id="password"
type="password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
+ required
+ autoComplete="new-password"
+ spellCheck={false}
+ onValueChange={() => {
+ if (confirmPasswordRef.current?.value)
+ formActionsRef.current?.validate('confirmPassword')
+ }}
placeholder={t(($) => $.passwordPlaceholder, { ns: 'login' }) || ''}
- className="mt-1"
/>
- <div className="mt-1 text-xs text-text-secondary">
- {t(($) => $['error.passwordInvalid'], { ns: 'login' })}
- </div>
- </div>
- {/* Confirm Password */}
- <div className="mb-5">
- <label
- htmlFor="confirmPassword"
- className="my-2 flex items-center justify-between text-sm font-medium text-text-primary"
- >
- {t(($) => $['account.confirmPassword'], { ns: 'common' })}
- </label>
+ <FieldValidity>
+ {({ validity }) =>
+ validity.valid !== false ? (
+ <FieldDescription>
+ {t(($) => $['error.passwordInvalid'], { ns: 'login' })}
+ </FieldDescription>
+ ) : null
+ }
+ </FieldValidity>
+ <FieldValidity>
+ {({ validity }) => (
+ <FieldError>
+ {t(
+ ($) =>
+ $[
+ validity.valueMissing ? 'error.passwordEmpty' : 'error.passwordInvalid'
+ ],
+ { ns: 'login' },
+ )}
+ </FieldError>
+ )}
+ </FieldValidity>
+ </Field>
+ <Field
+ name="confirmPassword"
+ validate={(value, formValues) => {
+ const confirmationValue = String(value)
+ return !confirmationValue || confirmationValue === formValues.password
+ ? null
+ : t(($) => $['account.notEqual'], { ns: 'common' })
+ }}
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $['account.confirmPassword'], { ns: 'common' })}</FieldLabel>
<Input
- id="confirmPassword"
type="password"
- value={confirmPassword}
- onChange={(e) => setConfirmPassword(e.target.value)}
+ required
+ autoComplete="new-password"
+ spellCheck={false}
+ ref={confirmPasswordRef}
placeholder={t(($) => $.confirmPasswordPlaceholder, { ns: 'login' }) || ''}
- className="mt-1"
/>
- </div>
- <div>
- <Button
- variant="primary"
- className="w-full text-sm!"
- onClick={handleChangePassword}
- >
- {t(($) => $['operation.reset'], { ns: 'common' })}
- </Button>
- </div>
- </div>
+ <FieldError>{t(($) => $['account.notEqual'], { ns: 'common' })}</FieldError>
+ </Field>
+ <Button
+ type="submit"
+ variant="primary"
+ className="w-full text-sm!"
+ loading={isSubmitting}
+ >
+ {t(($) => $['operation.reset'], { ns: 'common' })}
+ </Button>
+ </Form>
</div>
</div>
)}
@@ -167,7 +202,10 @@ const ChangePasswordForm = () => {
<div className="flex flex-col md:w-100">
<div className="mx-auto w-full">
<div className="mb-3 flex h-20 w-20 items-center justify-center rounded-[20px] border border-divider-regular bg-components-option-card-option-bg p-5 text-[40px] font-bold shadow-lg">
- <CheckCircleIcon className="h-10 w-10 text-[#039855]" />
+ <span
+ className="i-heroicons-check-circle-solid size-10 text-text-success"
+ aria-hidden="true"
+ />
</div>
<h1 className="text-[32px] font-bold text-text-primary">
{t(($) => $.passwordChangedTip, { ns: 'login' })}
diff --git a/web/app/forgot-password/ForgotPasswordForm.spec.tsx b/web/app/forgot-password/ForgotPasswordForm.spec.tsx
index 97fdaae9835..b4dfe22a2d6 100644
--- a/web/app/forgot-password/ForgotPasswordForm.spec.tsx
+++ b/web/app/forgot-password/ForgotPasswordForm.spec.tsx
@@ -1,5 +1,6 @@
import type { InitValidateStatusResponse, SetupStatusResponse } from '@/models/common'
-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 useDocumentTitle from '@/hooks/use-document-title'
import {
fetchInitValidateStatus,
@@ -47,27 +48,45 @@ describe('ForgotPasswordForm', () => {
})
it('should show validation error when email is empty', async () => {
+ const user = userEvent.setup()
render(<ForgotPasswordForm />)
- await screen.findByLabelText('login.email')
+ const emailInput = await screen.findByLabelText('login.email')
- fireEvent.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
+ await user.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
- await waitFor(() => {
- expect(screen.getByText('login.error.emailInValid')).toBeInTheDocument()
- })
+ const error = await screen.findByText('login.error.emailInValid')
+ expect(error).toHaveTextContent('login.error.emailInValid')
+ expect(emailInput).toHaveAttribute('aria-invalid', 'true')
+ expect(emailInput).toHaveAccessibleDescription('login.error.emailInValid')
+ expect(emailInput).toHaveFocus()
+ expect(mockSendForgotPasswordEmail).not.toHaveBeenCalled()
+ })
+
+ it('should reject an email that only passes native validation', async () => {
+ const user = userEvent.setup()
+ render(<ForgotPasswordForm />)
+
+ const emailInput = await screen.findByLabelText('login.email')
+ await user.type(emailInput, 'test@example')
+ await user.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
+
+ await screen.findByText('login.error.emailInValid')
+ expect(emailInput).toHaveAttribute('aria-invalid', 'true')
+ expect(emailInput).toHaveFocus()
expect(mockSendForgotPasswordEmail).not.toHaveBeenCalled()
})
it('should send the reset email and show a sign-in link after confirmation', async () => {
+ const user = userEvent.setup()
mockSendForgotPasswordEmail.mockResolvedValue({ result: 'success', data: 'ok' } as any)
render(<ForgotPasswordForm />)
const emailInput = await screen.findByLabelText('login.email')
- fireEvent.change(emailInput, { target: { value: '[email protected]' } })
+ await user.type(emailInput, '[email protected]')
- fireEvent.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
+ await user.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
await waitFor(() => {
expect(mockSendForgotPasswordEmail).toHaveBeenCalledWith({
@@ -86,18 +105,13 @@ describe('ForgotPasswordForm', () => {
})
it('should submit when form is submitted', async () => {
+ const user = userEvent.setup()
mockSendForgotPasswordEmail.mockResolvedValue({ result: 'success', data: 'ok' } as any)
render(<ForgotPasswordForm />)
- fireEvent.change(await screen.findByLabelText('login.email'), {
- target: { value: '[email protected]' },
- })
-
- const form = screen.getByRole('button', { name: /login\.sendResetLink/ }).closest('form')
- expect(form).not.toBeNull()
-
- fireEvent.submit(form as HTMLFormElement)
+ await user.type(await screen.findByLabelText('login.email'), '[email protected]')
+ await user.keyboard('{Enter}')
await waitFor(() => {
expect(mockSendForgotPasswordEmail).toHaveBeenCalledWith({
@@ -108,6 +122,7 @@ describe('ForgotPasswordForm', () => {
})
it('should disable submit while request is in flight', async () => {
+ const user = userEvent.setup()
let resolveRequest: ((value: any) => void) | undefined
const requestPromise = new Promise((resolve) => {
resolveRequest = resolve
@@ -116,18 +131,16 @@ describe('ForgotPasswordForm', () => {
render(<ForgotPasswordForm />)
- fireEvent.change(await screen.findByLabelText('login.email'), {
- target: { value: '[email protected]' },
- })
+ await user.type(await screen.findByLabelText('login.email'), '[email protected]')
const button = screen.getByRole('button', { name: /login\.sendResetLink/ })
- fireEvent.click(button)
+ await user.click(button)
await waitFor(() => {
- expect(button).toBeDisabled()
+ expect(button).toHaveAttribute('aria-disabled', 'true')
})
- fireEvent.click(button)
+ await user.click(button)
expect(mockSendForgotPasswordEmail).toHaveBeenCalledTimes(1)
resolveRequest?.({ result: 'success', data: 'ok' })
@@ -138,15 +151,14 @@ describe('ForgotPasswordForm', () => {
})
it('should keep form state when request fails', async () => {
+ const user = userEvent.setup()
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
mockSendForgotPasswordEmail.mockResolvedValue({ result: 'fail', data: 'error' } as any)
render(<ForgotPasswordForm />)
- fireEvent.change(await screen.findByLabelText('login.email'), {
- target: { value: '[email protected]' },
- })
- fireEvent.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
+ await user.type(await screen.findByLabelText('login.email'), '[email protected]')
+ await user.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
await waitFor(() => {
expect(mockSendForgotPasswordEmail).toHaveBeenCalledTimes(1)
diff --git a/web/app/forgot-password/ForgotPasswordForm.tsx b/web/app/forgot-password/ForgotPasswordForm.tsx
index 2c6c592abeb..b47ce212c47 100644
--- a/web/app/forgot-password/ForgotPasswordForm.tsx
+++ b/web/app/forgot-password/ForgotPasswordForm.tsx
@@ -2,13 +2,12 @@
import type { InitValidateStatusResponse } from '@/models/common'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { useStore } from '@tanstack/react-form'
-import * as React from 'react'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
+import { Input } from '@langgenius/dify-ui/input'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import * as z from 'zod'
-import { formContext, useAppForm } from '@/app/components/base/form'
-import { zodSubmitValidator } from '@/app/components/base/form/utils/zod-submit-validator'
import useDocumentTitle from '@/hooks/use-document-title'
import Link from '@/next/link'
import {
@@ -17,18 +16,20 @@ import {
sendForgotPasswordEmail,
} from '@/service/common'
import { basePath } from '@/utils/var'
-import Input from '../components/base/input'
import Loading from '../components/base/loading'
-const accountFormSchema = z.object({
- email: z.email('error.emailInValid').min(1, {
- error: 'error.emailInValid',
- }),
+type ForgotPasswordFormValues = {
+ email: string
+}
+
+const emailSchema = z.email('error.emailInValid').min(1, {
+ error: 'error.emailInValid',
})
const ForgotPasswordForm = () => {
const { t } = useTranslation()
const [loading, setLoading] = useState(true)
+ const [isSubmitting, setIsSubmitting] = useState(false)
const [isEmailSent, setIsEmailSent] = useState(false)
const documentTitle = loading
? t(($) => $.loading, { ns: 'common' })
@@ -37,32 +38,22 @@ const ForgotPasswordForm = () => {
: t(($) => $.forgotPassword, { ns: 'login' })
useDocumentTitle(documentTitle)
- const form = useAppForm({
- defaultValues: { email: '' },
- validators: {
- onSubmit: zodSubmitValidator(accountFormSchema),
- },
- onSubmit: async ({ value }) => {
- try {
- const res = await sendForgotPasswordEmail({
- url: '/forgot-password',
- body: { email: value.email },
- })
- if (res.result === 'success') setIsEmailSent(true)
- else console.error('Email verification failed')
- } catch (error) {
- console.error('Request failed:', error)
- }
- },
- })
-
- const isSubmitting = useStore(form.store, (state) => state.isSubmitting)
- const emailErrors = useStore(form.store, (state) => state.fieldMeta.email?.errors)
-
- const handleSendResetPasswordClick = () => {
+ const handleSubmit = async ({ email }: ForgotPasswordFormValues) => {
if (isSubmitting) return
- form.handleSubmit()
+ setIsSubmitting(true)
+ try {
+ const res = await sendForgotPasswordEmail({
+ url: '/forgot-password',
+ body: { email },
+ })
+ if (res.result === 'success') setIsEmailSent(true)
+ else console.error('Email verification failed')
+ } catch (error) {
+ console.error('Request failed:', error)
+ } finally {
+ setIsSubmitting(false)
+ }
}
useEffect(() => {
@@ -93,63 +84,42 @@ const ForgotPasswordForm = () => {
</div>
<div className="mt-8 grow sm:mx-auto sm:w-full sm:max-w-md">
<div className="relative">
- <formContext.Provider value={form}>
- <form
- onSubmit={(e) => {
- e.preventDefault()
- e.stopPropagation()
- form.handleSubmit()
- }}
- >
- {!isEmailSent && (
- <div className="mb-5">
- <label
- htmlFor="email"
- className="my-2 flex items-center justify-between text-sm font-medium text-text-primary"
- >
- {t(($) => $.email, { ns: 'login' })}
- </label>
- <div className="mt-1">
- <form.AppField name="email">
- {(field) => (
- <Input
- id="email"
- value={field.state.value}
- onChange={(e) => field.handleChange(e.target.value)}
- onBlur={field.handleBlur}
- placeholder={t(($) => $.emailPlaceholder, { ns: 'login' }) || ''}
- />
- )}
- </form.AppField>
- {emailErrors && emailErrors.length > 0 && (
- <span className="text-sm text-red-400">
- {t(($) => $[`${emailErrors[0]}` as 'error.emailInValid'], { ns: 'login' })}
- </span>
- )}
- </div>
- </div>
- )}
- <div>
- {isEmailSent ? (
- <Link
- href="/signin"
- className={cn(buttonVariants({ variant: 'primary' }), 'w-full')}
- >
- {t(($) => $.backToSignIn, { ns: 'login' })}
- </Link>
- ) : (
- <Button
- variant="primary"
- className="w-full"
- disabled={isSubmitting}
- onClick={handleSendResetPasswordClick}
- >
- {t(($) => $.sendResetLink, { ns: 'login' })}
- </Button>
- )}
- </div>
- </form>
- </formContext.Provider>
+ <Form<ForgotPasswordFormValues>
+ onFormSubmit={(value) => {
+ void handleSubmit(value)
+ }}
+ >
+ {!isEmailSent && (
+ <Field
+ name="email"
+ validate={(value) =>
+ emailSchema.safeParse(value).success
+ ? null
+ : t(($) => $['error.emailInValid'], { ns: 'login' })
+ }
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $.email, { ns: 'login' })}</FieldLabel>
+ <Input
+ type="email"
+ autoComplete="email"
+ spellCheck={false}
+ required
+ placeholder={t(($) => $.emailPlaceholder, { ns: 'login' }) || ''}
+ />
+ <FieldError>{t(($) => $['error.emailInValid'], { ns: 'login' })}</FieldError>
+ </Field>
+ )}
+ {isEmailSent ? (
+ <Link href="/signin" className={cn(buttonVariants({ variant: 'primary' }), 'w-full')}>
+ {t(($) => $.backToSignIn, { ns: 'login' })}
+ </Link>
+ ) : (
+ <Button type="submit" variant="primary" className="w-full" loading={isSubmitting}>
+ {t(($) => $.sendResetLink, { ns: 'login' })}
+ </Button>
+ )}
+ </Form>
</div>
</div>
</>
diff --git a/web/app/reset-password/__tests__/page.spec.tsx b/web/app/reset-password/__tests__/page.spec.tsx
new file mode 100644
index 00000000000..96664b20093
--- /dev/null
+++ b/web/app/reset-password/__tests__/page.spec.tsx
@@ -0,0 +1,88 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useLocale } from '@/context/i18n'
+import { useRouter, useSearchParams } from '@/next/navigation'
+import { sendResetPasswordCode } from '@/service/common'
+import ResetPasswordPage from '../page'
+
+const mockPush = vi.fn()
+const mockSetCountdownLeftTime = vi.fn()
+
+vi.mock('@/app/components/signin/storage', () => ({
+ COUNT_DOWN_TIME_MS: 60_000,
+ useSetCountdownLeftTime: () => mockSetCountdownLeftTime,
+}))
+
+vi.mock('@/context/i18n', () => ({
+ useLocale: vi.fn(),
+}))
+
+vi.mock('@/hooks/use-document-title', () => ({
+ default: vi.fn(),
+}))
+
+vi.mock('@/next/navigation', () => ({
+ useRouter: vi.fn(),
+ useSearchParams: vi.fn(),
+}))
+
+vi.mock('@/service/common', () => ({
+ sendResetPasswordCode: vi.fn(),
+}))
+
+describe('ResetPasswordPage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(useLocale).mockReturnValue('en-US')
+ vi.mocked(useRouter).mockReturnValue({ push: mockPush } as unknown as ReturnType<
+ typeof useRouter
+ >)
+ vi.mocked(useSearchParams).mockReturnValue(
+ new URLSearchParams() as unknown as ReturnType<typeof useSearchParams>,
+ )
+ vi.mocked(sendResetPasswordCode).mockResolvedValue({ result: 'success', data: 'reset-token' })
+ })
+
+ it('labels the email field and submits it with Enter', async () => {
+ const user = userEvent.setup()
+ render(<ResetPasswordPage />)
+
+ const emailInput = screen.getByRole('textbox', { name: 'login.email' })
+ expect(emailInput).toHaveAttribute('autocomplete', 'email')
+
+ await user.type(emailInput, '[email protected]{Enter}')
+
+ await waitFor(() => {
+ expect(sendResetPasswordCode).toHaveBeenCalledWith('[email protected]', 'en-US')
+ })
+ expect(mockPush).toHaveBeenCalledWith(
+ '/reset-password/check-code?token=reset-token&email=user%2540example.com',
+ )
+ })
+
+ it('keeps one associated error when an invalid email is cleared', async () => {
+ const user = userEvent.setup()
+ render(<ResetPasswordPage />)
+
+ const emailInput = screen.getByRole('textbox', { name: 'login.email' })
+ await user.type(emailInput, 'invalid-email{Enter}')
+
+ const invalidErrors = await screen.findAllByText('login.error.emailInValid')
+ expect(invalidErrors).toHaveLength(1)
+ expect(emailInput).toHaveAttribute('aria-invalid', 'true')
+ expect(emailInput).toHaveAccessibleDescription('login.error.emailInValid')
+ expect(emailInput).toHaveFocus()
+ expect(sendResetPasswordCode).not.toHaveBeenCalled()
+
+ await user.clear(emailInput)
+ await user.click(screen.getByRole('button', { name: 'login.sendVerificationCode' }))
+
+ const emptyErrors = await screen.findAllByText('login.error.emailEmpty')
+ expect(emptyErrors).toHaveLength(1)
+ expect(screen.queryByText('login.error.emailInValid')).not.toBeInTheDocument()
+ expect(emailInput).toHaveAttribute('aria-invalid', 'true')
+ expect(emailInput).toHaveAccessibleDescription('login.error.emailEmpty')
+ expect(emailInput).toHaveFocus()
+ expect(sendResetPasswordCode).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/app/reset-password/check-code/__tests__/page.spec.tsx b/web/app/reset-password/check-code/__tests__/page.spec.tsx
new file mode 100644
index 00000000000..06eb673a85d
--- /dev/null
+++ b/web/app/reset-password/check-code/__tests__/page.spec.tsx
@@ -0,0 +1,91 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useLocale } from '@/context/i18n'
+import { useRouter, useSearchParams } from '@/next/navigation'
+import { verifyResetPasswordCode } from '@/service/common'
+import CheckCodePage from '../page'
+
+const mockPush = vi.fn()
+
+vi.mock('@/app/components/signin/countdown', () => ({
+ default: () => null,
+}))
+
+vi.mock('@/context/i18n', () => ({
+ useLocale: vi.fn(),
+}))
+
+vi.mock('@/hooks/use-document-title', () => ({
+ default: vi.fn(),
+}))
+
+vi.mock('@/next/navigation', () => ({
+ useRouter: vi.fn(),
+ useSearchParams: vi.fn(),
+}))
+
+vi.mock('@/service/common', () => ({
+ sendResetPasswordCode: vi.fn(),
+ verifyResetPasswordCode: vi.fn(),
+}))
+
+describe('ResetPasswordCheckCodePage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(useLocale).mockReturnValue('en-US')
+ vi.mocked(useRouter).mockReturnValue({ push: mockPush } as unknown as ReturnType<
+ typeof useRouter
+ >)
+ vi.mocked(useSearchParams).mockReturnValue(
+ new URLSearchParams({
+ email: '[email protected]',
+ token: 'email-token',
+ }) as unknown as ReturnType<typeof useSearchParams>,
+ )
+ vi.mocked(verifyResetPasswordCode).mockResolvedValue({
+ result: 'success',
+ is_valid: true,
+ token: 'verified-token',
+ })
+ })
+
+ it('labels the one-time code field and submits it with Enter', async () => {
+ const user = userEvent.setup()
+ render(<CheckCodePage />)
+
+ const codeInput = screen.getByRole('textbox', {
+ name: 'login.checkCode.verificationCode',
+ })
+ expect(codeInput).toHaveAttribute('inputmode', 'numeric')
+ expect(codeInput).toHaveAttribute('autocomplete', 'one-time-code')
+
+ await user.type(codeInput, '123456{Enter}')
+
+ await waitFor(() => {
+ expect(verifyResetPasswordCode).toHaveBeenCalledWith({
+ code: '123456',
+ email: '[email protected]',
+ token: 'email-token',
+ })
+ })
+ expect(mockPush).toHaveBeenCalledWith(
+ '/reset-password/set-password?email=user%40example.com&token=verified-token',
+ )
+ })
+
+ it('associates an incomplete code error with the field', async () => {
+ const user = userEvent.setup()
+ render(<CheckCodePage />)
+
+ const codeInput = screen.getByRole('textbox', {
+ name: 'login.checkCode.verificationCode',
+ })
+ await user.type(codeInput, '123{Enter}')
+
+ const error = await screen.findByText('login.checkCode.invalidCode')
+ expect(codeInput).toHaveAttribute('aria-invalid', 'true')
+ expect(codeInput).toHaveAccessibleDescription(error.textContent ?? '')
+ expect(codeInput).toHaveFocus()
+ expect(verifyResetPasswordCode).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/app/reset-password/check-code/page.tsx b/web/app/reset-password/check-code/page.tsx
index 1b0e051ab7d..5d341f6b1d7 100644
--- a/web/app/reset-password/check-code/page.tsx
+++ b/web/app/reset-password/check-code/page.tsx
@@ -1,8 +1,9 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { toast } from '@langgenius/dify-ui/toast'
-import { RiArrowLeftLine, RiMailSendFill } from '@remixicon/react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import Countdown from '@/app/components/signin/countdown'
@@ -11,39 +12,35 @@ import useDocumentTitle from '@/hooks/use-document-title'
import { useRouter, useSearchParams } from '@/next/navigation'
import { sendResetPasswordCode, verifyResetPasswordCode } from '@/service/common'
+type CheckCodeFormValues = {
+ code: string
+}
+
export default function CheckCode() {
const { t } = useTranslation()
const router = useRouter()
const searchParams = useSearchParams()
const email = decodeURIComponent(searchParams.get('email') as string)
const token = decodeURIComponent(searchParams.get('token') as string)
- const [code, setVerifyCode] = useState('')
- const [loading, setIsLoading] = useState(false)
+ const [loading, setLoading] = useState(false)
const locale = useLocale()
const pageTitle = t(($) => $['checkCode.checkYourEmail'], { ns: 'login' })
useDocumentTitle(pageTitle)
- const verify = async () => {
+ const verify = async (code: string) => {
+ if (loading) return
try {
- if (!code.trim()) {
- toast.error(t(($) => $['checkCode.emptyCode'], { ns: 'login' }))
- return
- }
- if (!/\d{6}/.test(code)) {
- toast.error(t(($) => $['checkCode.invalidCode'], { ns: 'login' }))
- return
- }
- setIsLoading(true)
+ setLoading(true)
const ret = await verifyResetPasswordCode({ email, code, token })
if (ret.is_valid) {
const params = new URLSearchParams(searchParams)
params.set('token', encodeURIComponent(ret.token))
router.push(`/reset-password/set-password?${params.toString()}`)
- }
+ } else toast.error(t(($) => $['checkCode.invalidCode'], { ns: 'login' }))
} catch (error) {
console.error(error)
} finally {
- setIsLoading(false)
+ setLoading(false)
}
}
@@ -63,7 +60,7 @@ export default function CheckCode() {
return (
<div className="flex flex-col gap-3">
<div className="inline-flex size-14 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge text-text-accent-light-mode-only shadow-lg">
- <RiMailSendFill className="size-6 text-2xl" />
+ <span className="i-ri-mail-send-fill size-6" aria-hidden="true" />
</div>
<div className="pt-2 pb-4">
<h1 className="title-4xl-semi-bold text-text-primary">{pageTitle}</h1>
@@ -77,36 +74,36 @@ export default function CheckCode() {
</p>
</div>
- <form action="">
- <input type="text" className="hidden" />
- <label htmlFor="code" className="mb-1 system-md-semibold text-text-secondary">
- {t(($) => $['checkCode.verificationCode'], { ns: 'login' })}
- </label>
- <Input
- id="code"
- name="code"
- inputMode="numeric"
- autoComplete="one-time-code"
- spellCheck={false}
- value={code}
- onValueChange={setVerifyCode}
- maxLength={6}
- className="mt-1"
- placeholder={
- t(($) => $['checkCode.verificationCodePlaceholder'], { ns: 'login' }) as string
- }
- />
- <Button
- loading={loading}
- disabled={loading}
- className="my-3 w-full"
- variant="primary"
- onClick={verify}
- >
+ <Form<CheckCodeFormValues>
+ onFormSubmit={({ code }) => {
+ void verify(code)
+ }}
+ >
+ <Field name="code">
+ <FieldLabel>{t(($) => $['checkCode.verificationCode'], { ns: 'login' })}</FieldLabel>
+ <Input
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ spellCheck={false}
+ required
+ pattern="[0-9]{6}"
+ maxLength={6}
+ placeholder={
+ t(($) => $['checkCode.verificationCodePlaceholder'], { ns: 'login' }) as string
+ }
+ />
+ <FieldError match="valueMissing">
+ {t(($) => $['checkCode.emptyCode'], { ns: 'login' })}
+ </FieldError>
+ <FieldError match="patternMismatch">
+ {t(($) => $['checkCode.invalidCode'], { ns: 'login' })}
+ </FieldError>
+ </Field>
+ <Button type="submit" loading={loading} className="my-3 w-full" variant="primary">
{t(($) => $['checkCode.verify'], { ns: 'login' })}
</Button>
<Countdown onResend={resendCode} />
- </form>
+ </Form>
<div className="py-2">
<div className="h-px bg-linear-to-r from-background-gradient-mask-transparent via-divider-regular to-background-gradient-mask-transparent"></div>
</div>
@@ -116,7 +113,7 @@ export default function CheckCode() {
className="flex h-9 cursor-pointer appearance-none items-center justify-center text-text-tertiary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
>
<span className="inline-block rounded-full bg-background-default-dimmed p-1">
- <RiArrowLeftLine aria-hidden size={12} />
+ <span className="i-ri-arrow-left-line size-3" aria-hidden="true" />
</span>
<span className="ml-2 system-xs-regular">{t(($) => $.back, { ns: 'login' })}</span>
</button>
diff --git a/web/app/reset-password/page.tsx b/web/app/reset-password/page.tsx
index 3c1b6e5f26b..e3fc1ed7301 100644
--- a/web/app/reset-password/page.tsx
+++ b/web/app/reset-password/page.tsx
@@ -1,9 +1,9 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
+import { Field, FieldError, FieldLabel, FieldValidity } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { toast } from '@langgenius/dify-ui/toast'
-import { RiArrowLeftLine, RiLockPasswordLine } from '@remixicon/react'
-import { noop } from 'es-toolkit/function'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { emailRegex } from '@/config'
@@ -18,25 +18,16 @@ export default function CheckCode() {
const { t } = useTranslation()
const searchParams = useSearchParams()
const router = useRouter()
- const [email, setEmail] = useState('')
- const [loading, setIsLoading] = useState(false)
+ const [loading, setLoading] = useState(false)
const locale = useLocale()
const setCountdownLeftTime = useSetCountdownLeftTime()
const pageTitle = t(($) => $.resetPassword, { ns: 'login' })
useDocumentTitle(pageTitle)
- const handleGetEMailVerificationCode = async () => {
+ const handleGetEMailVerificationCode = async (email: string) => {
+ if (loading) return
try {
- if (!email) {
- toast.error(t(($) => $['error.emailEmpty'], { ns: 'login' }))
- return
- }
-
- if (!emailRegex.test(email)) {
- toast.error(t(($) => $['error.emailInValid'], { ns: 'login' }))
- return
- }
- setIsLoading(true)
+ setLoading(true)
const res = await sendResetPasswordCode(email, locale)
if (res.result === 'success') {
setCountdownLeftTime(`${COUNT_DOWN_TIME_MS}`)
@@ -50,14 +41,17 @@ export default function CheckCode() {
} catch (error) {
console.error(error)
} finally {
- setIsLoading(false)
+ setLoading(false)
}
}
return (
<div className="flex flex-col gap-3">
<div className="inline-flex size-14 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge shadow-lg">
- <RiLockPasswordLine className="size-6 text-2xl text-text-accent-light-mode-only" />
+ <span
+ className="i-ri-lock-password-line size-6 text-text-accent-light-mode-only"
+ aria-hidden="true"
+ />
</div>
<div className="pt-2 pb-4">
<h1 className="title-4xl-semi-bold text-text-primary">{pageTitle}</h1>
@@ -66,38 +60,43 @@ export default function CheckCode() {
</p>
</div>
- <form onSubmit={noop}>
- <input type="text" className="hidden" />
- <div className="mb-2">
- <label htmlFor="email" className="my-2 system-md-semibold text-text-secondary">
- {t(($) => $.email, { ns: 'login' })}
- </label>
- <div className="mt-1">
- <Input
- id="email"
- name="email"
- type="email"
- autoComplete="email"
- spellCheck={false}
- disabled={loading}
- value={email}
- placeholder={t(($) => $.emailPlaceholder, { ns: 'login' }) as string}
- onValueChange={setEmail}
- />
- </div>
- <div className="mt-3">
- <Button
- loading={loading}
- disabled={loading}
- variant="primary"
- className="w-full"
- onClick={handleGetEMailVerificationCode}
- >
- {t(($) => $.sendVerificationCode, { ns: 'login' })}
- </Button>
- </div>
- </div>
- </form>
+ <Form<{ email: string }>
+ onFormSubmit={({ email }) => {
+ void handleGetEMailVerificationCode(email)
+ }}
+ >
+ <Field
+ name="email"
+ validate={(value) => {
+ const emailValue = String(value)
+ return !emailValue || emailRegex.test(emailValue)
+ ? null
+ : t(($) => $['error.emailInValid'], { ns: 'login' })
+ }}
+ className="mb-3"
+ >
+ <FieldLabel>{t(($) => $.email, { ns: 'login' })}</FieldLabel>
+ <Input
+ type="email"
+ required
+ autoComplete="email"
+ spellCheck={false}
+ placeholder={t(($) => $.emailPlaceholder, { ns: 'login' }) as string}
+ />
+ <FieldValidity>
+ {({ validity }) => (
+ <FieldError>
+ {t(($) => $[validity.valueMissing ? 'error.emailEmpty' : 'error.emailInValid'], {
+ ns: 'login',
+ })}
+ </FieldError>
+ )}
+ </FieldValidity>
+ </Field>
+ <Button type="submit" loading={loading} variant="primary" className="w-full">
+ {t(($) => $.sendVerificationCode, { ns: 'login' })}
+ </Button>
+ </Form>
<div className="py-2">
<div className="h-px bg-linear-to-r from-background-gradient-mask-transparent via-divider-regular to-background-gradient-mask-transparent"></div>
</div>
@@ -106,7 +105,7 @@ export default function CheckCode() {
className="flex h-9 items-center justify-center text-text-tertiary hover:text-text-primary"
>
<div className="inline-block rounded-full bg-background-default-dimmed p-1">
- <RiArrowLeftLine size={12} />
+ <span className="i-ri-arrow-left-line size-3" aria-hidden="true" />
</div>
<span className="ml-2 system-xs-regular">{t(($) => $.backToLogin, { ns: 'login' })}</span>
</Link>
diff --git a/web/app/reset-password/set-password/__tests__/page.spec.tsx b/web/app/reset-password/set-password/__tests__/page.spec.tsx
index 769d6b0c3ea..86004a5df5d 100644
--- a/web/app/reset-password/set-password/__tests__/page.spec.tsx
+++ b/web/app/reset-password/set-password/__tests__/page.spec.tsx
@@ -1,4 +1,4 @@
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import useDocumentTitle from '@/hooks/use-document-title'
import { useRouter, useSearchParams } from '@/next/navigation'
@@ -54,17 +54,14 @@ const setSearchParams = (params: Record<string, string>) => {
}
const completePasswordChange = async () => {
+ const user = userEvent.setup()
render(<ChangePasswordForm />)
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('login.changePassword')
- fireEvent.change(screen.getByLabelText('common.account.newPassword'), {
- target: { value: 'ValidPass123!' },
- })
- fireEvent.change(screen.getByLabelText('common.account.confirmPassword'), {
- target: { value: 'ValidPass123!' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'login.changePasswordBtn' }))
+ await user.type(screen.getByLabelText('common.account.newPassword'), 'ValidPass123!')
+ await user.type(screen.getByLabelText('common.account.confirmPassword'), 'ValidPass123!')
+ await user.click(screen.getByRole('button', { name: 'login.changePasswordBtn' }))
await waitFor(() => {
expect(screen.getByRole('link', { name: /login\.passwordChanged/ })).toBeInTheDocument()
@@ -98,6 +95,7 @@ describe('Reset Password Set Password Page', () => {
const confirmPasswordInput = screen.getByLabelText('common.account.confirmPassword')
expect(passwordInput).toHaveAttribute('autocomplete', 'new-password')
+ expect(passwordInput).toHaveAccessibleDescription('login.error.passwordInvalid')
expect(confirmPasswordInput).toHaveAttribute('autocomplete', 'new-password')
await user.type(passwordInput, 'ValidPass123!')
@@ -120,6 +118,31 @@ describe('Reset Password Set Password Page', () => {
})
})
+ it('revalidates the confirmation field when the password changes', async () => {
+ const user = userEvent.setup()
+ render(<ChangePasswordForm />)
+
+ const passwordInput = screen.getByLabelText('common.account.newPassword')
+ await user.type(passwordInput, 'ValidPass123!')
+ const confirmPasswordInput = screen.getByLabelText('common.account.confirmPassword')
+ await user.type(confirmPasswordInput, 'DifferentPass123!{Enter}')
+
+ const error = await screen.findByText('common.account.notEqual')
+ expect(confirmPasswordInput).toHaveAttribute('aria-invalid', 'true')
+ expect(confirmPasswordInput).toHaveAccessibleDescription(error.textContent ?? '')
+ expect(confirmPasswordInput).toHaveFocus()
+ expect(mockChangePasswordWithToken).not.toHaveBeenCalled()
+
+ await user.clear(passwordInput)
+ await user.type(passwordInput, 'DifferentPass123!')
+
+ await waitFor(() => {
+ expect(screen.queryByText('common.account.notEqual')).not.toBeInTheDocument()
+ })
+ expect(confirmPasswordInput).not.toHaveAttribute('aria-invalid', 'true')
+ expect(mockChangePasswordWithToken).not.toHaveBeenCalled()
+ })
+
describe('Post-reset navigation', () => {
it('should preserve redirect_url when the user returns to sign in manually', async () => {
setSearchParams({ token: 'reset-token', redirect_url: redirectUrl })
diff --git a/web/app/reset-password/set-password/page.tsx b/web/app/reset-password/set-password/page.tsx
index 69aa3fb3aa1..8d06c3f3e34 100644
--- a/web/app/reset-password/set-password/page.tsx
+++ b/web/app/reset-password/set-password/page.tsx
@@ -1,14 +1,19 @@
'use client'
+import type { FormActions } from '@langgenius/dify-ui/form'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FieldValidity,
+} from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
-import { toast } from '@langgenius/dify-ui/toast'
-import { RiCheckboxCircleFill } from '@remixicon/react'
import { useCountDown } from 'ahooks'
-import { useCallback, useState } from 'react'
+import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { validPassword } from '@/config'
import useDocumentTitle from '@/hooks/use-document-title'
@@ -16,14 +21,20 @@ import Link from '@/next/link'
import { useRouter, useSearchParams } from '@/next/navigation'
import { changePasswordWithToken } from '@/service/common'
+type PasswordFormValues = {
+ password: string
+ confirmPassword: string
+}
+
const ChangePasswordForm = () => {
const { t } = useTranslation()
const router = useRouter()
const searchParams = useSearchParams()
const token = decodeURIComponent(searchParams.get('token') || '')
- const [password, setPassword] = useState('')
- const [confirmPassword, setConfirmPassword] = useState('')
+ const formActionsRef = useRef<FormActions>(null)
+ const confirmPasswordRef = useRef<HTMLInputElement>(null)
+ const [isSubmitting, setIsSubmitting] = useState(false)
const [showSuccess, setShowSuccess] = useState(false)
const [showPassword, setShowPassword] = useState(false)
const [showConfirmPassword, setShowConfirmPassword] = useState(false)
@@ -33,10 +44,6 @@ const ChangePasswordForm = () => {
: t(($) => $.changePassword, { ns: 'login' }),
)
- const showErrorMessage = useCallback((message: string) => {
- toast.error(message)
- }, [])
-
const getSignInUrl = () => {
if (searchParams.has('invite_token')) {
const params = new URLSearchParams()
@@ -63,39 +70,29 @@ const ChangePasswordForm = () => {
},
})
- const valid = useCallback(() => {
- if (!password.trim()) {
- showErrorMessage(t(($) => $['error.passwordEmpty'], { ns: 'login' }))
- return false
- }
- if (!validPassword.test(password)) {
- showErrorMessage(t(($) => $['error.passwordInvalid'], { ns: 'login' }))
- return false
- }
- if (password !== confirmPassword) {
- showErrorMessage(t(($) => $['account.notEqual'], { ns: 'common' }))
- return false
- }
- return true
- }, [password, confirmPassword, showErrorMessage, t])
-
- const handleChangePassword = useCallback(async () => {
- if (!valid()) return
- try {
- await changePasswordWithToken({
- url: '/forgot-password/resets',
- body: {
- token,
- new_password: password,
- password_confirm: confirmPassword,
- },
- })
- setShowSuccess(true)
- setLeftTime(AUTO_REDIRECT_TIME)
- } catch (error) {
- console.error(error)
- }
- }, [password, token, valid, confirmPassword])
+ const handleChangePassword = useCallback(
+ async (formValues: PasswordFormValues) => {
+ if (isSubmitting) return
+ setIsSubmitting(true)
+ try {
+ await changePasswordWithToken({
+ url: '/forgot-password/resets',
+ body: {
+ token,
+ new_password: formValues.password,
+ password_confirm: formValues.confirmPassword,
+ },
+ })
+ setShowSuccess(true)
+ setLeftTime(AUTO_REDIRECT_TIME)
+ } catch (error) {
+ console.error(error)
+ } finally {
+ setIsSubmitting(false)
+ }
+ },
+ [isSubmitting, token],
+ )
return (
<div
@@ -113,18 +110,33 @@ const ChangePasswordForm = () => {
</div>
<div className="mx-auto mt-6 w-full">
- <Form onFormSubmit={() => void handleChangePassword()}>
- <Field name="password" className="mb-5">
- <FieldLabel className="py-0 system-md-semibold text-text-secondary">
- {t(($) => $['account.newPassword'], { ns: 'common' })}
- </FieldLabel>
+ <Form<PasswordFormValues>
+ actionsRef={formActionsRef}
+ onFormSubmit={(formValues) => void handleChangePassword(formValues)}
+ >
+ <Field
+ name="password"
+ validate={(value) => {
+ const passwordValue = String(value)
+ if (!passwordValue.trim())
+ return t(($) => $['error.passwordEmpty'], { ns: 'login' })
+ return validPassword.test(passwordValue)
+ ? null
+ : t(($) => $['error.passwordInvalid'], { ns: 'login' })
+ }}
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $['account.newPassword'], { ns: 'common' })}</FieldLabel>
<InputGroup>
<InputGroupInput
type={showPassword ? 'text' : 'password'}
+ required
autoComplete="new-password"
spellCheck={false}
- value={password}
- onValueChange={setPassword}
+ onValueChange={() => {
+ if (confirmPasswordRef.current?.value)
+ formActionsRef.current?.validate('confirmPassword')
+ }}
placeholder={t(($) => $.passwordPlaceholder, { ns: 'login' }) || ''}
/>
<InputGroupAddon align="inline-end">
@@ -143,21 +155,47 @@ const ChangePasswordForm = () => {
</IconButton>
</InputGroupAddon>
</InputGroup>
- <FieldDescription className="py-0 body-xs-regular text-text-secondary">
- {t(($) => $['error.passwordInvalid'], { ns: 'login' })}
- </FieldDescription>
+ <FieldValidity>
+ {({ validity }) =>
+ validity.valid !== false ? (
+ <FieldDescription>
+ {t(($) => $['error.passwordInvalid'], { ns: 'login' })}
+ </FieldDescription>
+ ) : null
+ }
+ </FieldValidity>
+ <FieldValidity>
+ {({ validity }) => (
+ <FieldError>
+ {t(
+ ($) =>
+ $[
+ validity.valueMissing ? 'error.passwordEmpty' : 'error.passwordInvalid'
+ ],
+ { ns: 'login' },
+ )}
+ </FieldError>
+ )}
+ </FieldValidity>
</Field>
- <Field name="confirmPassword" className="mb-5">
- <FieldLabel className="py-0 system-md-semibold text-text-secondary">
- {t(($) => $['account.confirmPassword'], { ns: 'common' })}
- </FieldLabel>
+ <Field
+ name="confirmPassword"
+ validate={(value, formValues) => {
+ const confirmationValue = String(value)
+ return !confirmationValue || confirmationValue === formValues.password
+ ? null
+ : t(($) => $['account.notEqual'], { ns: 'common' })
+ }}
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $['account.confirmPassword'], { ns: 'common' })}</FieldLabel>
<InputGroup>
<InputGroupInput
type={showConfirmPassword ? 'text' : 'password'}
+ required
autoComplete="new-password"
spellCheck={false}
- value={confirmPassword}
- onValueChange={setConfirmPassword}
+ ref={confirmPasswordRef}
placeholder={t(($) => $.confirmPasswordPlaceholder, { ns: 'login' }) || ''}
/>
<InputGroupAddon align="inline-end">
@@ -177,8 +215,9 @@ const ChangePasswordForm = () => {
</IconButton>
</InputGroupAddon>
</InputGroup>
+ <FieldError>{t(($) => $['account.notEqual'], { ns: 'common' })}</FieldError>
</Field>
- <Button type="submit" variant="primary" className="w-full">
+ <Button type="submit" variant="primary" className="w-full" loading={isSubmitting}>
{t(($) => $.changePasswordBtn, { ns: 'login' })}
</Button>
</Form>
@@ -189,7 +228,10 @@ const ChangePasswordForm = () => {
<div className="flex flex-col md:w-100">
<div className="mx-auto w-full">
<div className="mb-3 flex size-14 items-center justify-center rounded-2xl border border-components-panel-border-subtle font-bold shadow-lg">
- <RiCheckboxCircleFill aria-hidden="true" className="size-6 text-text-success" />
+ <span
+ className="i-ri-checkbox-circle-fill size-6 text-text-success"
+ aria-hidden="true"
+ />
</div>
<h1 className="title-4xl-semi-bold text-text-primary">
{t(($) => $.passwordChangedTip, { ns: 'login' })}
diff --git a/web/app/signin/__tests__/normal-form.spec.tsx b/web/app/signin/__tests__/normal-form.spec.tsx
index afe46929163..30819cc8566 100644
--- a/web/app/signin/__tests__/normal-form.spec.tsx
+++ b/web/app/signin/__tests__/normal-form.spec.tsx
@@ -1,5 +1,6 @@
import { useQuery } from '@tanstack/react-query'
-import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { useRouter, useSearchParams } from '@/next/navigation'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
@@ -217,7 +218,8 @@ describe('NormalForm', () => {
})
})
- it('should describe password visibility through its changing action name', () => {
+ it('should describe password visibility through its changing action name', async () => {
+ const user = userEvent.setup()
mockQueryResults(
nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,
nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,
@@ -228,7 +230,7 @@ describe('NormalForm', () => {
const showPasswordButton = screen.getByRole('button', { name: 'login.showPassword' })
expect(showPasswordButton).not.toHaveAttribute('aria-pressed')
- fireEvent.click(showPasswordButton)
+ await user.click(showPasswordButton)
expect(screen.getByRole('button', { name: 'login.hidePassword' })).not.toHaveAttribute(
'aria-pressed',
@@ -236,6 +238,50 @@ describe('NormalForm', () => {
expect(screen.getByLabelText('login.password')).toHaveAttribute('type', 'text')
})
+ it('keeps credential inputs together before secondary password actions in the tab order', async () => {
+ const user = userEvent.setup()
+ mockQueryResults(
+ nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,
+ nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,
+ )
+
+ render(<NormalForm />, {
+ systemFeatures: { is_email_setup: true },
+ })
+
+ const emailInput = screen.getByLabelText('login.email')
+ await user.click(emailInput)
+
+ await user.tab()
+ expect(screen.getByLabelText('login.password')).toHaveFocus()
+
+ await user.tab()
+ expect(screen.getByRole('button', { name: 'login.showPassword' })).toHaveFocus()
+
+ await user.tab()
+ expect(screen.getByRole('link', { name: 'login.forget' })).toHaveFocus()
+ })
+
+ it('associates input validation errors with the invalid credential field', async () => {
+ const user = userEvent.setup()
+ mockQueryResults(
+ nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,
+ nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,
+ )
+
+ render(<NormalForm />)
+
+ const emailInput = screen.getByLabelText('login.email')
+ await user.type(emailInput, 'invalid-email')
+ await user.type(screen.getByLabelText('login.password'), 'password')
+ await user.click(screen.getByRole('button', { name: 'login.signBtn' }))
+
+ const error = await screen.findByText('login.error.emailInValid')
+ expect(emailInput).toHaveAttribute('aria-invalid', 'true')
+ expect(emailInput).toHaveAccessibleDescription(error.textContent ?? '')
+ expect(emailInput).toHaveFocus()
+ })
+
it('should not expose SSO when it is enforced without a configured protocol', () => {
mockQueryResults(
nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,
diff --git a/web/app/signin/__tests__/one-more-step.spec.tsx b/web/app/signin/__tests__/one-more-step.spec.tsx
index b995ca0c009..94572f750ca 100644
--- a/web/app/signin/__tests__/one-more-step.spec.tsx
+++ b/web/app/signin/__tests__/one-more-step.spec.tsx
@@ -63,7 +63,8 @@ describe('OneMoreStep', () => {
</QueryClientProvider>,
)
- await user.click(screen.getByRole('button', { name: 'login.go' }))
+ await user.click(screen.getByRole('textbox', { name: 'login.invitationCode' }))
+ await user.keyboard('{Enter}')
await waitFor(() => {
expect(mockReplace).toHaveBeenCalledWith('/apps?tag=workflow')
diff --git a/web/app/signin/check-code/__tests__/page.spec.tsx b/web/app/signin/check-code/__tests__/page.spec.tsx
index 2700fd73629..632ce1ac6b7 100644
--- a/web/app/signin/check-code/__tests__/page.spec.tsx
+++ b/web/app/signin/check-code/__tests__/page.spec.tsx
@@ -207,7 +207,7 @@ describe('CheckCode', () => {
expect(navigationMocks.back).toHaveBeenCalledOnce()
})
- it('rejects verification codes that are not exactly six digits', async () => {
+ it('associates one localized error with an incomplete verification code', async () => {
const user = userEvent.setup()
const queryClient = createQueryClient()
render(
@@ -216,11 +216,14 @@ describe('CheckCode', () => {
</QueryClientProvider>,
)
- fireEvent.change(screen.getByLabelText('login.checkCode.verificationCode'), {
- target: { value: '1234567' },
- })
- await user.click(screen.getByRole('button', { name: 'login.checkCode.verify' }))
+ const codeInput = screen.getByLabelText('login.checkCode.verificationCode')
+ await user.type(codeInput, '12345{Enter}')
+ const errors = await screen.findAllByText('login.checkCode.invalidCode')
+ expect(errors).toHaveLength(1)
+ expect(codeInput).toHaveAttribute('aria-invalid', 'true')
+ expect(codeInput).toHaveAccessibleDescription('login.checkCode.invalidCode')
+ expect(codeInput).toHaveFocus()
expect(emailLoginWithCode).not.toHaveBeenCalled()
})
diff --git a/web/app/signin/check-code/page.tsx b/web/app/signin/check-code/page.tsx
index 56e82f35fb1..79410779fe6 100644
--- a/web/app/signin/check-code/page.tsx
+++ b/web/app/signin/check-code/page.tsx
@@ -1,9 +1,9 @@
'use client'
-import type { FormEvent } from 'react'
import { Button } from '@langgenius/dify-ui/button'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { toast } from '@langgenius/dify-ui/toast'
-import { RiArrowLeftLine, RiMailSendFill } from '@remixicon/react'
import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -24,6 +24,10 @@ import { basePath } from '@/utils/var'
import Turnstile from '../components/turnstile'
import { resolvePostLoginRedirect } from '../utils/post-login-redirect'
+type CheckCodeFormValues = {
+ code: string
+}
+
export default function CheckCode() {
const { t, i18n } = useTranslation()
const router = useRouter()
@@ -34,8 +38,7 @@ export default function CheckCode() {
const token = decodeURIComponent(searchParams.get('token') as string)
const invite_token = decodeURIComponent(searchParams.get('invite_token') || '')
const language = i18n.language
- const [code, setVerifyCode] = useState('')
- const [loading, setIsLoading] = useState(false)
+ const [loading, setLoading] = useState(false)
const [isResending, setIsResending] = useState(false)
const [verifyTurnstileToken, setVerifyTurnstileToken] = useState('')
const [verifyTurnstileGeneration, setVerifyTurnstileGeneration] = useState(0)
@@ -50,22 +53,14 @@ export default function CheckCode() {
const pageTitle = t(($) => $['checkCode.checkYourEmail'], { ns: 'login' })
useDocumentTitle(pageTitle)
- const verify = async () => {
+ const verify = async (code: string) => {
if (loading || isResending || showResendTurnstile) return
let shouldResetTurnstile = false
try {
- if (!code.trim()) {
- toast.error(t(($) => $['checkCode.emptyCode'], { ns: 'login' }))
- return
- }
- if (!/^\d{6}$/.test(code)) {
- toast.error(t(($) => $['checkCode.invalidCode'], { ns: 'login' }))
- return
- }
if (isTurnstileRequired && !verifyTurnstileToken) return
- setIsLoading(true)
+ setLoading(true)
shouldResetTurnstile = isTurnstileRequired
const ret = await emailLoginWithCode({
email,
@@ -90,11 +85,13 @@ export default function CheckCode() {
await queryClient.fetchQuery(profileQueryOptions)
replaceLoginRedirect(resolvePostLoginRedirect(searchParams), router.replace, basePath)
}
+ } else {
+ toast.error(ret.data)
}
} catch (error) {
console.error(error)
} finally {
- setIsLoading(false)
+ setLoading(false)
if (shouldResetTurnstile) {
setVerifyTurnstileToken('')
setVerifyTurnstileGeneration((value) => value + 1)
@@ -102,11 +99,6 @@ export default function CheckCode() {
}
}
- const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault()
- verify()
- }
-
useEffect(() => {
codeInputRef.current?.focus()
}, [])
@@ -148,7 +140,10 @@ export default function CheckCode() {
return (
<div className="flex flex-col gap-3">
<div className="inline-flex size-14 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge shadow-lg">
- <RiMailSendFill className="size-6 text-2xl text-text-accent-light-mode-only" />
+ <span
+ className="i-ri-mail-send-fill size-6 text-text-accent-light-mode-only"
+ aria-hidden="true"
+ />
</div>
<div className="pt-2 pb-4">
<h1 className="title-4xl-semi-bold text-text-primary">{pageTitle}</h1>
@@ -162,24 +157,28 @@ export default function CheckCode() {
</p>
</div>
- <form onSubmit={handleSubmit}>
- <label htmlFor="code" className="mb-1 system-md-semibold text-text-secondary">
- {t(($) => $['checkCode.verificationCode'], { ns: 'login' })}
- </label>
- <Input
- ref={codeInputRef}
- id="code"
- name="code"
- inputMode="numeric"
- autoComplete="one-time-code"
- value={code}
- onChange={(e) => setVerifyCode(e.target.value)}
- maxLength={6}
- className="mt-1"
- placeholder={
- t(($) => $['checkCode.verificationCodePlaceholder'], { ns: 'login' }) as string
- }
- />
+ <Form<CheckCodeFormValues> onFormSubmit={({ code }) => void verify(code)}>
+ <Field name="code">
+ <FieldLabel>{t(($) => $['checkCode.verificationCode'], { ns: 'login' })}</FieldLabel>
+ <Input
+ ref={codeInputRef}
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ spellCheck={false}
+ required
+ pattern="[0-9]{6}"
+ maxLength={6}
+ placeholder={
+ t(($) => $['checkCode.verificationCodePlaceholder'], { ns: 'login' }) as string
+ }
+ />
+ <FieldError match="valueMissing">
+ {t(($) => $['checkCode.emptyCode'], { ns: 'login' })}
+ </FieldError>
+ <FieldError match="patternMismatch">
+ {t(($) => $['checkCode.invalidCode'], { ns: 'login' })}
+ </FieldError>
+ </Field>
{shouldRenderTurnstile && (
<Turnstile
action={showResendTurnstile ? 'signin_code' : 'signin_code_verify'}
@@ -208,10 +207,7 @@ export default function CheckCode() {
type="submit"
loading={loading}
disabled={
- loading ||
- isResending ||
- showResendTurnstile ||
- (isTurnstileRequired && !verifyTurnstileToken)
+ isResending || showResendTurnstile || (isTurnstileRequired && !verifyTurnstileToken)
}
className="my-3 w-full"
variant="primary"
@@ -229,7 +225,7 @@ export default function CheckCode() {
}
restartOnResend={false}
/>
- </form>
+ </Form>
<div className="py-2">
<div className="h-px bg-linear-to-r from-background-gradient-mask-transparent via-divider-regular to-background-gradient-mask-transparent"></div>
</div>
@@ -239,7 +235,7 @@ export default function CheckCode() {
className="flex h-9 cursor-pointer appearance-none items-center justify-center text-text-tertiary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
>
<span className="inline-block rounded-full bg-background-default-dimmed p-1">
- <RiArrowLeftLine aria-hidden size={12} />
+ <span className="i-ri-arrow-left-line size-3" aria-hidden="true" />
</span>
<span className="ml-2 system-xs-regular">{t(($) => $.back, { ns: 'login' })}</span>
</button>
diff --git a/web/app/signin/components/__tests__/mail-and-code-auth.spec.tsx b/web/app/signin/components/__tests__/mail-and-code-auth.spec.tsx
index 8a3f04a43a7..acd71774a45 100644
--- a/web/app/signin/components/__tests__/mail-and-code-auth.spec.tsx
+++ b/web/app/signin/components/__tests__/mail-and-code-auth.spec.tsx
@@ -213,6 +213,20 @@ describe('MailAndCodeAuth', () => {
expect(mocks.render).not.toHaveBeenCalled()
})
+ it('associates one localized error with an invalid email', async () => {
+ const user = userEvent.setup()
+ renderMailAndCodeAuth('COMMUNITY')
+
+ const emailInput = screen.getByRole('textbox', { name: 'login.email' })
+ await user.type(emailInput, 'invalid-email{Enter}')
+
+ const errors = await screen.findAllByText('login.error.emailInValid')
+ expect(errors).toHaveLength(1)
+ expect(emailInput).toHaveAttribute('aria-invalid', 'true')
+ expect(emailInput).toHaveAccessibleDescription('login.error.emailInValid')
+ expect(mocks.sendEMailLoginCode).not.toHaveBeenCalled()
+ })
+
it('keeps SaaS email-code login disabled when the Turnstile site key is missing', async () => {
const user = userEvent.setup()
mocks.turnstileSiteKey = ''
diff --git a/web/app/signin/components/mail-and-code-auth.tsx b/web/app/signin/components/mail-and-code-auth.tsx
index 70fad97c88a..9cc9f41b3ab 100644
--- a/web/app/signin/components/mail-and-code-auth.tsx
+++ b/web/app/signin/components/mail-and-code-auth.tsx
@@ -1,8 +1,7 @@
import { Button } from '@langgenius/dify-ui/button'
-import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
-import { toast } from '@langgenius/dify-ui/toast'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -35,17 +34,9 @@ export default function MailAndCodeAuth({ isInvite }: MailAndCodeAuthProps) {
const shouldRenderTurnstile = isTurnstileRequired && Boolean(turnstileSiteKey)
const handleGetEMailVerificationCode = async () => {
+ if (loading) return
let shouldResetTurnstile = false
try {
- if (!email) {
- toast.error(t(($) => $['error.emailEmpty'], { ns: 'login' }))
- return
- }
-
- if (!emailRegex.test(email)) {
- toast.error(t(($) => $['error.emailInValid'], { ns: 'login' }))
- return
- }
setLoading(true)
shouldResetTurnstile = isTurnstileRequired
const ret = await sendEMailLoginCode(
@@ -78,20 +69,34 @@ export default function MailAndCodeAuth({ isInvite }: MailAndCodeAuthProps) {
void handleGetEMailVerificationCode()
}}
>
- <Field name="email" disabled={isInvite} className="mb-2">
- <FieldLabel className="my-2 py-0 system-md-semibold text-text-secondary">
- {t(($) => $.email, { ns: 'login' })}
- </FieldLabel>
+ <Field
+ name="email"
+ disabled={isInvite}
+ validate={(value) => {
+ const emailValue = String(value)
+ return !emailValue || emailRegex.test(emailValue)
+ ? null
+ : t(($) => $['error.emailInValid'], { ns: 'login' })
+ }}
+ className={shouldRenderTurnstile ? 'mb-1' : 'mb-4'}
+ >
+ <FieldLabel>{t(($) => $.email, { ns: 'login' })}</FieldLabel>
<Input
type="email"
autoComplete="email"
spellCheck={false}
disabled={isInvite}
+ required
value={email}
placeholder={t(($) => $.emailPlaceholder, { ns: 'login' }) as string}
onValueChange={setEmail}
/>
- {shouldRenderTurnstile && (
+ <FieldError>
+ {t(($) => $[email ? 'error.emailInValid' : 'error.emailEmpty'], { ns: 'login' })}
+ </FieldError>
+ </Field>
+ {shouldRenderTurnstile && (
+ <div className="mb-4">
<Turnstile
key={turnstileGeneration}
action="signin_code"
@@ -104,19 +109,17 @@ export default function MailAndCodeAuth({ isInvite }: MailAndCodeAuthProps) {
setTurnstileToken('')
}}
/>
- )}
- <div className="mt-3">
- <Button
- type="submit"
- loading={loading}
- disabled={loading || !email || (isTurnstileRequired && !turnstileToken)}
- variant="primary"
- className="w-full"
- >
- {t(($) => $['signup.verifyMail'], { ns: 'login' })}
- </Button>
</div>
- </Field>
+ )}
+ <Button
+ type="submit"
+ loading={loading}
+ disabled={isTurnstileRequired && !turnstileToken}
+ variant="primary"
+ className="w-full"
+ >
+ {t(($) => $['signup.verifyMail'], { ns: 'login' })}
+ </Button>
</Form>
)
}
diff --git a/web/app/signin/components/mail-and-password-auth.tsx b/web/app/signin/components/mail-and-password-auth.tsx
index 5f490b4a857..62cf7980f46 100644
--- a/web/app/signin/components/mail-and-password-auth.tsx
+++ b/web/app/signin/components/mail-and-password-auth.tsx
@@ -1,5 +1,5 @@
import { Button } from '@langgenius/dify-ui/button'
-import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
@@ -48,23 +48,10 @@ export default function MailAndPasswordAuth({ isInvite, isEmailSetup }: MailAndP
const emailFromLink = decodeURIComponent(searchParams.get('email') || '')
const [email, setEmail] = useState(emailFromLink)
const [password, setPassword] = useState('')
-
const [isLoading, setIsLoading] = useState(false)
const handleEmailPasswordLogin = async () => {
- if (!email) {
- toast.error(t(($) => $['error.emailEmpty'], { ns: 'login' }))
- return
- }
- if (!emailRegex.test(email)) {
- toast.error(t(($) => $['error.emailInValid'], { ns: 'login' }))
- return
- }
- if (!password?.trim()) {
- toast.error(t(($) => $['error.passwordEmpty'], { ns: 'login' }))
- return
- }
-
+ if (isLoading) return
try {
setIsLoading(true)
const loginData: LoginRequestBody = {
@@ -99,9 +86,8 @@ export default function MailAndPasswordAuth({ isInvite, isEmailSetup }: MailAndP
toast.error(res.data)
}
} catch (error) {
- if (hasErrorCode(error, 'authentication_failed')) {
+ if (hasErrorCode(error, 'authentication_failed'))
toast.error(t(($) => $['error.invalidEmailOrPassword'], { ns: 'login' }))
- }
} finally {
setIsLoading(false)
}
@@ -113,40 +99,41 @@ export default function MailAndPasswordAuth({ isInvite, isEmailSetup }: MailAndP
void handleEmailPasswordLogin()
}}
>
- <Field name="email" disabled={isInvite} className="mb-3">
- <FieldLabel className="my-2 py-0 system-md-semibold text-text-secondary">
- {t(($) => $.email, { ns: 'login' })}
- </FieldLabel>
+ <Field
+ name="email"
+ disabled={isInvite}
+ validate={(value) => {
+ const emailValue = String(value)
+ return !emailValue || emailRegex.test(emailValue)
+ ? null
+ : t(($) => $['error.emailInValid'], { ns: 'login' })
+ }}
+ className="mb-3"
+ >
+ <FieldLabel>{t(($) => $.email, { ns: 'login' })}</FieldLabel>
<Input
value={email}
onValueChange={setEmail}
disabled={isInvite}
type="email"
+ required
autoComplete="email"
spellCheck={false}
placeholder={t(($) => $.emailPlaceholder, { ns: 'login' }) || ''}
/>
+ <FieldError>
+ {t(($) => $[email ? 'error.emailInValid' : 'error.emailEmpty'], { ns: 'login' })}
+ </FieldError>
</Field>
- <Field name="password" className="mb-3">
- <div className="my-2 flex items-center justify-between">
- <FieldLabel className="py-0 system-md-semibold text-text-secondary">
- {t(($) => $.password, { ns: 'login' })}
- </FieldLabel>
- <Link
- href={`/reset-password?${searchParams.toString()}`}
- className={`system-xs-regular ${isEmailSetup ? 'text-components-button-secondary-accent-text' : 'pointer-events-none text-components-button-secondary-accent-text-disabled'}`}
- tabIndex={isEmailSetup ? 0 : -1}
- aria-disabled={!isEmailSetup}
- >
- {t(($) => $.forget, { ns: 'login' })}
- </Link>
- </div>
- <InputGroup className="mt-1">
+ <Field name="password" className="relative mb-3">
+ <FieldLabel>{t(($) => $.password, { ns: 'login' })}</FieldLabel>
+ <InputGroup>
<InputGroupInput
value={password}
onValueChange={setPassword}
type={showPassword ? 'text' : 'password'}
+ required
autoComplete="current-password"
spellCheck={false}
placeholder={t(($) => $.passwordPlaceholder, { ns: 'login' }) || ''}
@@ -167,16 +154,23 @@ export default function MailAndPasswordAuth({ isInvite, isEmailSetup }: MailAndP
</IconButton>
</InputGroupAddon>
</InputGroup>
+ <Link
+ href={`/reset-password?${searchParams.toString()}`}
+ className={`absolute end-0 top-1 rounded-sm system-xs-regular outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid ${isEmailSetup ? 'text-components-button-secondary-accent-text' : 'pointer-events-none text-components-button-secondary-accent-text-disabled'}`}
+ tabIndex={isEmailSetup ? 0 : -1}
+ aria-disabled={!isEmailSetup}
+ >
+ {t(($) => $.forget, { ns: 'login' })}
+ </Link>
+ <FieldError>
+ {t(($) => $[password.trim() ? 'error.passwordInvalid' : 'error.passwordEmpty'], {
+ ns: 'login',
+ })}
+ </FieldError>
</Field>
<div className="mb-2">
- <Button
- type="submit"
- loading={isLoading}
- variant="primary"
- disabled={isLoading || !email || !password}
- className="w-full"
- >
+ <Button type="submit" loading={isLoading} variant="primary" className="w-full">
{t(($) => $.signBtn, { ns: 'login' })}
</Button>
</div>
diff --git a/web/app/signin/invite-settings/__tests__/page.spec.tsx b/web/app/signin/invite-settings/__tests__/page.spec.tsx
index eee0d16e611..712a6f7bf55 100644
--- a/web/app/signin/invite-settings/__tests__/page.spec.tsx
+++ b/web/app/signin/invite-settings/__tests__/page.spec.tsx
@@ -1,6 +1,7 @@
import type { MockedFunction } from 'vite-plus/test'
import { useQuery } from '@tanstack/react-query'
-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 { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { useLocale } from '@/context/i18n'
import { useRouter, useSearchParams } from '@/next/navigation'
@@ -155,13 +156,25 @@ describe('InviteSettingsPage', () => {
})
describe('Activation payload', () => {
+ it('associates a missing name error with the account field', async () => {
+ const user = userEvent.setup()
+ render(<InviteSettingsPage />)
+
+ const nameInput = screen.getByLabelText('login.name')
+ await user.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
+
+ const error = await screen.findByText('login.enterYourName')
+ expect(nameInput).toHaveAttribute('aria-invalid', 'true')
+ expect(nameInput).toHaveAccessibleDescription(error.textContent ?? '')
+ expect(nameInput).toHaveFocus()
+ expect(mockActivateMember).not.toHaveBeenCalled()
+ })
+
it('should default language to the current UI locale', async () => {
+ const user = userEvent.setup()
render(<InviteSettingsPage />)
- fireEvent.change(screen.getByLabelText('login.name'), {
- target: { value: 'Invitee' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
+ await user.type(screen.getByLabelText('login.name'), 'Invitee{Enter}')
await waitFor(() => {
expect(mockActivateMember).toHaveBeenCalledWith({
@@ -177,14 +190,13 @@ describe('InviteSettingsPage', () => {
})
it('should fall back to configured default locale when current locale is unsupported', async () => {
+ const user = userEvent.setup()
mockUseLocale.mockReturnValue('unsupported-locale' as ReturnType<typeof useLocale>)
render(<InviteSettingsPage />)
- fireEvent.change(screen.getByLabelText('login.name'), {
- target: { value: 'Invitee' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
+ await user.type(screen.getByLabelText('login.name'), 'Invitee')
+ await user.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
await waitFor(() => {
expect(mockActivateMember).toHaveBeenCalledWith({
@@ -200,6 +212,7 @@ describe('InviteSettingsPage', () => {
})
it('should only submit the token when an active account accepts an invitation', async () => {
+ const user = userEvent.setup()
mockUseInvitationCheck.mockReturnValue({
data: {
is_valid: true,
@@ -217,7 +230,7 @@ describe('InviteSettingsPage', () => {
render(<InviteSettingsPage />)
expect(screen.queryByLabelText('login.name')).not.toBeInTheDocument()
- fireEvent.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
+ await user.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
await waitFor(() => {
expect(mockActivateMember).toHaveBeenCalledWith({
@@ -230,6 +243,7 @@ describe('InviteSettingsPage', () => {
})
it('should only submit the token when an active account check omits setup state', async () => {
+ const user = userEvent.setup()
mockUseInvitationCheck.mockReturnValue({
data: {
is_valid: true,
@@ -246,7 +260,7 @@ describe('InviteSettingsPage', () => {
render(<InviteSettingsPage />)
expect(screen.queryByLabelText('login.name')).not.toBeInTheDocument()
- fireEvent.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
+ await user.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
await waitFor(() => {
expect(mockActivateMember).toHaveBeenCalledWith({
@@ -259,6 +273,7 @@ describe('InviteSettingsPage', () => {
})
it('should submit setup fields when the invitation requires account setup', async () => {
+ const user = userEvent.setup()
mockUseInvitationCheck.mockReturnValue({
data: {
is_valid: true,
@@ -275,10 +290,8 @@ describe('InviteSettingsPage', () => {
render(<InviteSettingsPage />)
- fireEvent.change(screen.getByLabelText('login.name'), {
- target: { value: 'Invitee' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
+ await user.type(screen.getByLabelText('login.name'), 'Invitee')
+ await user.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
await waitFor(() => {
expect(mockActivateMember).toHaveBeenCalledWith({
@@ -296,6 +309,7 @@ describe('InviteSettingsPage', () => {
describe('Post-activation redirect', () => {
it('should use the console home when the redirect target is external', async () => {
+ const user = userEvent.setup()
mockUseSearchParams.mockReturnValue(
new URLSearchParams(
'invite_token=invite-token&redirect_url=https%3A%2F%2Fgoogle.com',
@@ -304,10 +318,8 @@ describe('InviteSettingsPage', () => {
render(<InviteSettingsPage />)
- fireEvent.change(screen.getByLabelText('login.name'), {
- target: { value: 'Invitee' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
+ await user.type(screen.getByLabelText('login.name'), 'Invitee')
+ await user.click(screen.getByRole('button', { name: 'Rejoindre Acme' }))
await waitFor(() => {
expect(mockReplace).toHaveBeenCalledWith('/')
diff --git a/web/app/signin/invite-settings/page.tsx b/web/app/signin/invite-settings/page.tsx
index 150d1dad000..03fe6109ee2 100644
--- a/web/app/signin/invite-settings/page.tsx
+++ b/web/app/signin/invite-settings/page.tsx
@@ -2,6 +2,8 @@
import type { Locale } from '@/i18n-config'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import {
Select,
@@ -9,12 +11,10 @@ import {
SelectItem,
SelectItemIndicator,
SelectItemText,
+ SelectLabel,
SelectTrigger,
} from '@langgenius/dify-ui/select'
-import { toast } from '@langgenius/dify-ui/toast'
-import { RiAccountCircleLine } from '@remixicon/react'
import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
-import { noop } from 'es-toolkit/function'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
@@ -141,11 +141,8 @@ export default function InviteSettingsPage() {
const handleActivate = useCallback(async () => {
try {
+ if (isActivating) return
if (!isInvitationForCurrentAccount) return
- if (requiresAccountSetup && !name) {
- toast.error(t(($) => $.enterYourName, { ns: 'login' }))
- return
- }
setIsActivating(true)
const body = requiresAccountSetup
? {
@@ -173,6 +170,7 @@ export default function InviteSettingsPage() {
}
}, [
isInvitationForCurrentAccount,
+ isActivating,
language,
name,
queryClient,
@@ -182,7 +180,6 @@ export default function InviteSettingsPage() {
timezone,
token,
router,
- t,
])
if (isProfilePending || shouldReturnToSignIn || !checkRes) return <Loading />
@@ -212,7 +209,10 @@ export default function InviteSettingsPage() {
return (
<div className="flex flex-col gap-3">
<div className="inline-flex size-14 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge shadow-lg">
- <RiAccountCircleLine className="size-6 text-2xl text-text-accent-light-mode-only" />
+ <span
+ className="i-ri-account-circle-line size-6 text-text-accent-light-mode-only"
+ aria-hidden="true"
+ />
</div>
<div className="pt-2 pb-4">
<h1 className="title-4xl-semi-bold text-text-primary">
@@ -221,93 +221,71 @@ export default function InviteSettingsPage() {
: workspaceInvitationTitle}
</h1>
</div>
- <form onSubmit={noop}>
+ <Form
+ onFormSubmit={() => {
+ void handleActivate()
+ }}
+ >
{requiresAccountSetup && (
<>
- <div className="mb-5">
- <label htmlFor="name" className="my-2 system-md-semibold text-text-secondary">
- {t(($) => $.name, { ns: 'login' })}
- </label>
- <div className="mt-1">
- <Input
- id="name"
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder={t(($) => $.namePlaceholder, { ns: 'login' }) || ''}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault()
- e.stopPropagation()
- handleActivate()
- }
- }}
- />
- </div>
- </div>
- <div className="mb-5">
- <label
- htmlFor="interface_language"
- className="my-2 system-md-semibold text-text-secondary"
- >
- {t(($) => $.interfaceLanguage, { ns: 'login' })}
- </label>
- <div className="mt-1">
- <Select
- value={selectedLanguage?.value ?? null}
- onValueChange={handleLanguageChange}
- >
- <SelectTrigger id="interface_language" size="large">
- {selectedLanguage?.name ?? t(($) => $['placeholder.select'], { ns: 'common' })}
- </SelectTrigger>
- <SelectContent>
- {LANGUAGE_OPTIONS.map((item) => (
- <SelectItem key={item.value} value={item.value}>
- <SelectItemText>{item.name}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
- <div className="mb-5">
- <label htmlFor="timezone" className="system-md-semibold text-text-secondary">
- {t(($) => $.timezone, { ns: 'login' })}
- </label>
- <div className="mt-1">
- <Select
- value={selectedTimezone?.value ?? null}
- onValueChange={handleTimezoneChange}
- >
- <SelectTrigger id="timezone" size="large">
- {selectedTimezone?.name ?? t(($) => $['placeholder.select'], { ns: 'common' })}
- </SelectTrigger>
- <SelectContent>
- {TIMEZONE_OPTIONS.map((item) => (
- <SelectItem key={item.value} value={item.value}>
- <SelectItemText>{item.name}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
+ <Field
+ name="name"
+ validate={(value) => {
+ const nameValue = String(value)
+ return !nameValue || nameValue.trim()
+ ? null
+ : t(($) => $.enterYourName, { ns: 'login' })
+ }}
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $.name, { ns: 'login' })}</FieldLabel>
+ <Input
+ type="text"
+ required
+ value={name}
+ onValueChange={setName}
+ placeholder={t(($) => $.namePlaceholder, { ns: 'login' }) || ''}
+ />
+ <FieldError>{t(($) => $.enterYourName, { ns: 'login' })}</FieldError>
+ </Field>
+ <Field name="interface_language" className="mb-5">
+ <Select value={selectedLanguage?.value ?? null} onValueChange={handleLanguageChange}>
+ <SelectLabel>{t(($) => $.interfaceLanguage, { ns: 'login' })}</SelectLabel>
+ <SelectTrigger size="large">
+ {selectedLanguage?.name ?? t(($) => $['placeholder.select'], { ns: 'common' })}
+ </SelectTrigger>
+ <SelectContent>
+ {LANGUAGE_OPTIONS.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ <SelectItemText>{item.name}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ <Field name="timezone" className="mb-5">
+ <Select value={selectedTimezone?.value ?? null} onValueChange={handleTimezoneChange}>
+ <SelectLabel>{t(($) => $.timezone, { ns: 'login' })}</SelectLabel>
+ <SelectTrigger size="large">
+ {selectedTimezone?.name ?? t(($) => $['placeholder.select'], { ns: 'common' })}
+ </SelectTrigger>
+ <SelectContent>
+ {TIMEZONE_OPTIONS.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ <SelectItemText>{item.name}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
</>
)}
- <div>
- <Button
- variant="primary"
- className="w-full"
- onClick={handleActivate}
- loading={isActivating}
- disabled={isActivating}
- >
- {workspaceInvitationTitle}
- </Button>
- </div>
- </form>
+ <Button type="submit" variant="primary" className="w-full" loading={isActivating}>
+ {workspaceInvitationTitle}
+ </Button>
+ </Form>
{!systemFeatures.branding.enabled && (
<div className="mt-2 block w-full system-xs-regular text-text-tertiary">
{t(($) => $['license.tip'], { ns: 'login' })}
diff --git a/web/app/signin/one-more-step.tsx b/web/app/signin/one-more-step.tsx
index a2fdbba195b..1c9f081271c 100644
--- a/web/app/signin/one-more-step.tsx
+++ b/web/app/signin/one-more-step.tsx
@@ -1,6 +1,9 @@
'use client'
import type { Reducer } from 'react'
import { Button } from '@langgenius/dify-ui/button'
+import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
+import { Input } from '@langgenius/dify-ui/input'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import {
Select,
@@ -8,6 +11,7 @@ import {
SelectItem,
SelectItemIndicator,
SelectItemText,
+ SelectLabel,
SelectTrigger,
} from '@langgenius/dify-ui/select'
import { toast } from '@langgenius/dify-ui/toast'
@@ -24,7 +28,6 @@ import { useOneMoreStep } from '@/service/use-common'
import { replaceLoginRedirect } from '@/utils/login-redirect.client'
import { timezones } from '@/utils/timezone'
import { basePath } from '@/utils/var'
-import Input from '../components/base/input'
type IState = {
invitation_code: string
@@ -33,7 +36,6 @@ type IState = {
}
type IAction =
- | { type: 'failed'; payload: null }
| { type: 'invitation_code'; value: string }
| { type: 'interface_language'; value: string }
| { type: 'timezone'; value: string }
@@ -46,12 +48,6 @@ const reducer: Reducer<IState, IAction> = (state: IState, action: IAction) => {
return { ...state, interface_language: action.value }
case 'timezone':
return { ...state, timezone: action.value }
- case 'failed':
- return {
- invitation_code: '',
- interface_language: 'en-US',
- timezone: 'Asia/Shanghai',
- }
default:
throw new Error('Unknown action.')
}
@@ -106,7 +102,7 @@ const OneMoreStep = () => {
if (isPending) return
try {
await submitOneMoreStep({
- invitation_code: state.invitation_code,
+ invitation_code: state.invitation_code.trim(),
interface_language: state.interface_language,
timezone: state.timezone,
})
@@ -115,7 +111,6 @@ const OneMoreStep = () => {
} catch (error: unknown) {
if (hasStatus(error) && error.status === 400)
toast.error(t(($) => $.invalidInvitationCode, { ns: 'login' }))
- dispatch({ type: 'failed', payload: null })
}
}
@@ -131,17 +126,22 @@ const OneMoreStep = () => {
</div>
<div className="mx-auto mt-6 w-full">
- <div className="relative">
- <div className="mb-5">
- <div className="my-2 flex items-center justify-between system-md-semibold text-text-secondary">
- <label htmlFor="invitation_code">{t(($) => $.invitationCode, { ns: 'login' })}</label>
+ <Form
+ className="relative"
+ onFormSubmit={() => {
+ void handleSubmit()
+ }}
+ >
+ <Field name="invitation_code" className="mb-5">
+ <div className="flex items-center justify-between system-md-semibold text-text-secondary">
+ <FieldLabel>{t(($) => $.invitationCode, { ns: 'login' })}</FieldLabel>
<Popover>
<PopoverTrigger
openOnHover
render={
<button
type="button"
- className="cursor-pointer rounded-sm text-text-accent-secondary outline-hidden focus-visible:ring-1 focus-visible:ring-components-input-border-hover"
+ className="cursor-pointer rounded-sm text-text-accent-secondary outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"
>
{t(($) => $.dontHave, { ns: 'login' })}
</button>
@@ -162,71 +162,48 @@ const OneMoreStep = () => {
</PopoverContent>
</Popover>
</div>
- <div className="mt-1">
- <Input
- id="invitation_code"
- value={state.invitation_code}
- type="text"
- placeholder={t(($) => $.invitationCodePlaceholder, { ns: 'login' }) || ''}
- onChange={(e) => {
- dispatch({ type: 'invitation_code', value: e.target.value.trim() })
- }}
- />
- </div>
- </div>
- <div className="mb-5">
- <label
- htmlFor="interface_language"
- className="my-2 system-md-semibold text-text-secondary"
- >
- {t(($) => $.interfaceLanguage, { ns: 'login' })}
- </label>
- <div className="mt-1">
- <Select value={selectedLanguage?.value ?? null} onValueChange={handleLanguageChange}>
- <SelectTrigger id="interface_language" size="large">
- {selectedLanguage?.name ?? t(($) => $['placeholder.select'], { ns: 'common' })}
- </SelectTrigger>
- <SelectContent>
- {LANGUAGE_OPTIONS.map((item) => (
- <SelectItem key={item.value} value={item.value}>
- <SelectItemText>{item.name}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
- <div className="mb-4">
- <label htmlFor="timezone" className="system-md-semibold text-text-tertiary">
- {t(($) => $.timezone, { ns: 'login' })}
- </label>
- <div className="mt-1">
- <Select value={selectedTimezone?.value ?? null} onValueChange={handleTimezoneChange}>
- <SelectTrigger id="timezone" size="large">
- {selectedTimezone?.name ?? t(($) => $['placeholder.select'], { ns: 'common' })}
- </SelectTrigger>
- <SelectContent>
- {TIMEZONE_OPTIONS.map((item) => (
- <SelectItem key={item.value} value={item.value}>
- <SelectItemText>{item.name}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
- <div>
- <Button
- variant="primary"
- className="w-full"
- disabled={isPending}
- onClick={handleSubmit}
- >
- {t(($) => $.go, { ns: 'login' })}
- </Button>
- </div>
+ <Input
+ value={state.invitation_code}
+ type="text"
+ placeholder={t(($) => $.invitationCodePlaceholder, { ns: 'login' }) || ''}
+ onValueChange={(value) => dispatch({ type: 'invitation_code', value })}
+ />
+ </Field>
+ <Field name="interface_language" className="mb-5">
+ <Select value={selectedLanguage?.value ?? null} onValueChange={handleLanguageChange}>
+ <SelectLabel>{t(($) => $.interfaceLanguage, { ns: 'login' })}</SelectLabel>
+ <SelectTrigger size="large">
+ {selectedLanguage?.name ?? t(($) => $['placeholder.select'], { ns: 'common' })}
+ </SelectTrigger>
+ <SelectContent>
+ {LANGUAGE_OPTIONS.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ <SelectItemText>{item.name}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ <Field name="timezone" className="mb-4">
+ <Select value={selectedTimezone?.value ?? null} onValueChange={handleTimezoneChange}>
+ <SelectLabel>{t(($) => $.timezone, { ns: 'login' })}</SelectLabel>
+ <SelectTrigger size="large">
+ {selectedTimezone?.name ?? t(($) => $['placeholder.select'], { ns: 'common' })}
+ </SelectTrigger>
+ <SelectContent>
+ {TIMEZONE_OPTIONS.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ <SelectItemText>{item.name}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ <Button type="submit" variant="primary" className="w-full" loading={isPending}>
+ {t(($) => $.go, { ns: 'login' })}
+ </Button>
<div className="mt-2 block w-full system-xs-regular text-text-tertiary">
{t(($) => $['license.tip'], { ns: 'login' })}
&nbsp;
@@ -239,7 +216,7 @@ const OneMoreStep = () => {
{t(($) => $['license.link'], { ns: 'login' })}
</Link>
</div>
- </div>
+ </Form>
</div>
</>
)
diff --git a/web/app/signup/check-code/__tests__/page.spec.tsx b/web/app/signup/check-code/__tests__/page.spec.tsx
index 9b1e0160774..43e91c033ad 100644
--- a/web/app/signup/check-code/__tests__/page.spec.tsx
+++ b/web/app/signup/check-code/__tests__/page.spec.tsx
@@ -75,7 +75,6 @@ describe('Signup Check Code Page', () => {
const codeInput = screen.getByRole('textbox', {
name: 'login.checkCode.verificationCode',
})
- expect(codeInput).toHaveAttribute('id', 'code')
expect(codeInput).toHaveAttribute('name', 'code')
expect(codeInput).toHaveAttribute('inputmode', 'numeric')
expect(codeInput).toHaveAttribute('autocomplete', 'one-time-code')
@@ -95,4 +94,21 @@ describe('Signup Check Code Page', () => {
})
expect(mockVerifyCode).toHaveBeenCalledTimes(1)
})
+
+ it('associates one localized error with an incomplete verification code', async () => {
+ const user = userEvent.setup()
+ render(<CheckCode />)
+
+ const codeInput = screen.getByRole('textbox', {
+ name: 'login.checkCode.verificationCode',
+ })
+ await user.type(codeInput, '12345{Enter}')
+
+ const errors = await screen.findAllByText('login.checkCode.invalidCode')
+ expect(errors).toHaveLength(1)
+ expect(codeInput).toHaveAttribute('aria-invalid', 'true')
+ expect(codeInput).toHaveAccessibleDescription('login.checkCode.invalidCode')
+ expect(codeInput).toHaveFocus()
+ expect(mockVerifyCode).not.toHaveBeenCalled()
+ })
})
diff --git a/web/app/signup/check-code/page.tsx b/web/app/signup/check-code/page.tsx
index e1e495e891a..8ab5c895e77 100644
--- a/web/app/signup/check-code/page.tsx
+++ b/web/app/signup/check-code/page.tsx
@@ -1,10 +1,10 @@
'use client'
import type { MailSendResponse, MailValidityResponse } from '@/service/use-common'
import { Button } from '@langgenius/dify-ui/button'
-import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { toast } from '@langgenius/dify-ui/toast'
-import { RiArrowLeftLine, RiMailSendFill } from '@remixicon/react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import Countdown from '@/app/components/signin/countdown'
@@ -13,32 +13,27 @@ import useDocumentTitle from '@/hooks/use-document-title'
import { useRouter, useSearchParams } from '@/next/navigation'
import { useMailValidity, useSendMail } from '@/service/use-common'
+type CheckCodeFormValues = {
+ code: string
+}
+
export default function CheckCode() {
const { t } = useTranslation()
const router = useRouter()
const searchParams = useSearchParams()
const email = decodeURIComponent(searchParams.get('email') as string)
- const [token, setToken] = useState(decodeURIComponent(searchParams.get('token') as string))
- const [code, setVerifyCode] = useState('')
- const [loading, setIsLoading] = useState(false)
+ const [token, setToken] = useState(() => decodeURIComponent(searchParams.get('token') as string))
+ const [loading, setLoading] = useState(false)
const locale = useLocale()
const { mutateAsync: submitMail } = useSendMail()
const { mutateAsync: verifyCode } = useMailValidity()
const pageTitle = t(($) => $['checkCode.checkYourEmail'], { ns: 'login' })
useDocumentTitle(pageTitle)
- const verify = async () => {
+ const verify = async (code: string) => {
if (loading) return
try {
- if (!code.trim()) {
- toast.error(t(($) => $['checkCode.emptyCode'], { ns: 'login' }))
- return
- }
- if (!/\d{6}/.test(code)) {
- toast.error(t(($) => $['checkCode.invalidCode'], { ns: 'login' }))
- return
- }
- setIsLoading(true)
+ setLoading(true)
const res = await verifyCode({ email, code, token })
if ((res as MailValidityResponse).is_valid) {
const params = new URLSearchParams(searchParams)
@@ -50,7 +45,7 @@ export default function CheckCode() {
} catch (error) {
console.error(error)
} finally {
- setIsLoading(false)
+ setLoading(false)
}
}
@@ -72,7 +67,10 @@ export default function CheckCode() {
return (
<div className="flex flex-col gap-3">
<div className="inline-flex size-14 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge shadow-lg">
- <RiMailSendFill className="size-6 text-2xl text-text-accent-light-mode-only" />
+ <span
+ className="i-ri-mail-send-fill size-6 text-text-accent-light-mode-only"
+ aria-hidden="true"
+ />
</div>
<div className="pt-2 pb-4">
<h1 className="title-4xl-semi-bold text-text-primary">{pageTitle}</h1>
@@ -86,35 +84,36 @@ export default function CheckCode() {
</p>
</div>
- <form
- onSubmit={(event) => {
- event.preventDefault()
- void verify()
+ <Form<CheckCodeFormValues>
+ onFormSubmit={({ code }) => {
+ void verify(code)
}}
>
<Field name="code">
- <FieldLabel htmlFor="code" className="mb-1 system-md-semibold text-text-secondary">
- {t(($) => $['checkCode.verificationCode'], { ns: 'login' })}
- </FieldLabel>
+ <FieldLabel>{t(($) => $['checkCode.verificationCode'], { ns: 'login' })}</FieldLabel>
<Input
- id="code"
- name="code"
- value={code}
- onValueChange={setVerifyCode}
maxLength={6}
inputMode="numeric"
autoComplete="one-time-code"
- className="mt-1"
+ spellCheck={false}
+ required
+ pattern="[0-9]{6}"
placeholder={
t(($) => $['checkCode.verificationCodePlaceholder'], { ns: 'login' }) as string
}
/>
+ <FieldError match="valueMissing">
+ {t(($) => $['checkCode.emptyCode'], { ns: 'login' })}
+ </FieldError>
+ <FieldError match="patternMismatch">
+ {t(($) => $['checkCode.invalidCode'], { ns: 'login' })}
+ </FieldError>
</Field>
<Button type="submit" loading={loading} className="my-3 w-full" variant="primary">
{t(($) => $['checkCode.verify'], { ns: 'login' })}
</Button>
<Countdown onResend={resendCode} />
- </form>
+ </Form>
<div className="py-2">
<div className="h-px bg-linear-to-r from-background-gradient-mask-transparent via-divider-regular to-background-gradient-mask-transparent"></div>
</div>
@@ -124,7 +123,7 @@ export default function CheckCode() {
className="flex h-9 cursor-pointer appearance-none items-center justify-center text-text-tertiary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
>
<span className="bg-background-default-dimm inline-block rounded-full p-1">
- <RiArrowLeftLine aria-hidden size={12} />
+ <span className="i-ri-arrow-left-line size-3" aria-hidden="true" />
</span>
<span className="ml-2 system-xs-regular">{t(($) => $.back, { ns: 'login' })}</span>
</button>
diff --git a/web/app/signup/components/input-mail.spec.tsx b/web/app/signup/components/input-mail.spec.tsx
index cc517e386c6..42b6f6a2830 100644
--- a/web/app/signup/components/input-mail.spec.tsx
+++ b/web/app/signup/components/input-mail.spec.tsx
@@ -1,5 +1,5 @@
import type { MockedFunction } from 'vite-plus/test'
-import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { useLocale } from '@/context/i18n'
@@ -152,27 +152,30 @@ describe('InputMail Form', () => {
// Validation and failure paths.
describe('Edge Cases', () => {
- it('should block submission when email is invalid', () => {
- const { container } = renderForm()
- const form = container.querySelector('form')
+ it('should block submission when email is invalid', async () => {
+ const user = userEvent.setup()
+ renderForm()
const input = screen.getByLabelText('login.email')
- fireEvent.change(input, { target: { value: 'invalid-email' } })
- expect(form).not.toBeNull()
- fireEvent.submit(form as HTMLFormElement)
+ await user.type(input, 'invalid-email{Enter}')
+ const error = await screen.findByText('login.error.emailInValid')
+ expect(input).toHaveAttribute('aria-invalid', 'true')
+ expect(input).toHaveAccessibleDescription(error.textContent ?? '')
+ expect(input).toHaveFocus()
expect(mockSubmitMail).not.toHaveBeenCalled()
expect(mockOnSuccess).not.toHaveBeenCalled()
})
it('should not call onSuccess when mutation does not succeed', async () => {
+ const user = userEvent.setup()
mockSubmitMail.mockResolvedValue({ result: 'failed', data: 'token' })
renderForm()
const input = screen.getByLabelText('login.email')
const button = screen.getByRole('button', { name: 'login.signup.verifyMail' })
- fireEvent.change(input, { target: { value: '[email protected]' } })
- fireEvent.click(button)
+ await user.type(input, '[email protected]')
+ await user.click(button)
await waitFor(() => {
expect(mockSubmitMail).toHaveBeenCalled()
diff --git a/web/app/signup/components/input-mail.tsx b/web/app/signup/components/input-mail.tsx
index 8312e837747..eb817a8c0f9 100644
--- a/web/app/signup/components/input-mail.tsx
+++ b/web/app/signup/components/input-mail.tsx
@@ -1,12 +1,10 @@
'use client'
import type { MailSendResponse } from '@/service/use-common'
import { Button } from '@langgenius/dify-ui/button'
-import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Field, FieldError, FieldLabel, FieldValidity } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
-import { toast } from '@langgenius/dify-ui/toast'
import { useSuspenseQuery } from '@tanstack/react-query'
-import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Split from '@/app/signin/split'
import { emailRegex } from '@/config'
@@ -19,9 +17,13 @@ import { useSendMail } from '@/service/use-common'
type Props = {
onSuccess: (email: string, payload: string) => void
}
+
+type SignupEmailFormValues = {
+ email: string
+}
+
export default function SignupEmailForm({ onSuccess }: Props) {
const { t } = useTranslation()
- const [email, setEmail] = useState('')
const locale = useLocale()
const searchParams = useSearchParams()
const queryString = searchParams.toString()
@@ -30,44 +32,45 @@ export default function SignupEmailForm({ onSuccess }: Props) {
const { mutateAsync: submitMail, isPending } = useSendMail()
- const handleSubmit = useCallback(async () => {
+ const handleSubmit = async (email: string) => {
if (isPending) return
-
- if (!email) {
- toast.error(t(($) => $['error.emailEmpty'], { ns: 'login' }))
- return
- }
- if (!emailRegex.test(email)) {
- toast.error(t(($) => $['error.emailInValid'], { ns: 'login' }))
- return
- }
const res = await submitMail({ email, language: locale })
if ((res as MailSendResponse).result === 'success')
onSuccess(email, (res as MailSendResponse).data)
- }, [email, locale, submitMail, t, isPending, onSuccess])
+ }
return (
- <Form
- onSubmit={(e) => {
- e.preventDefault()
- handleSubmit()
- }}
- >
- <Field name="email" className="mb-3">
- <FieldLabel className="py-0 text-[14px] leading-5 font-semibold text-text-secondary">
- {t(($) => $.email, { ns: 'login' })}
- </FieldLabel>
+ <Form<SignupEmailFormValues> onFormSubmit={({ email }) => void handleSubmit(email)}>
+ <Field
+ name="email"
+ validate={(value) => {
+ const emailValue = String(value)
+ return !emailValue || emailRegex.test(emailValue)
+ ? null
+ : t(($) => $['error.emailInValid'], { ns: 'login' })
+ }}
+ className="mb-3"
+ >
+ <FieldLabel>{t(($) => $.email, { ns: 'login' })}</FieldLabel>
<Input
- value={email}
- onValueChange={setEmail}
type="email"
+ required
autoComplete="email"
spellCheck={false}
placeholder={t(($) => $.emailPlaceholder, { ns: 'login' }) || ''}
/>
+ <FieldValidity>
+ {({ validity }) => (
+ <FieldError>
+ {t(($) => $[validity.valueMissing ? 'error.emailEmpty' : 'error.emailInValid'], {
+ ns: 'login',
+ })}
+ </FieldError>
+ )}
+ </FieldValidity>
</Field>
<div className="mb-2">
- <Button variant="primary" type="submit" disabled={isPending || !email} className="w-full">
+ <Button variant="primary" type="submit" loading={isPending} className="w-full">
{t(($) => $['signup.verifyMail'], { ns: 'login' })}
</Button>
</div>
diff --git a/web/app/signup/set-password/__tests__/page.spec.tsx b/web/app/signup/set-password/__tests__/page.spec.tsx
index 02bff2877f0..1fdfab5daf8 100644
--- a/web/app/signup/set-password/__tests__/page.spec.tsx
+++ b/web/app/signup/set-password/__tests__/page.spec.tsx
@@ -1,7 +1,7 @@
import type { ReactElement } from 'react'
import type { MockedFunction } from 'vite-plus/test'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-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 Cookies from 'js-cookie'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
@@ -108,6 +108,7 @@ describe('Signup Set Password Page', () => {
const confirmPasswordInput = screen.getByLabelText('common.account.confirmPassword')
expect(passwordInput).toHaveAttribute('autocomplete', 'new-password')
+ expect(passwordInput).toHaveAccessibleDescription('login.error.passwordInvalid')
expect(confirmPasswordInput).toHaveAttribute('autocomplete', 'new-password')
await user.type(passwordInput, 'ValidPass123!')
@@ -123,26 +124,48 @@ describe('Signup Set Password Page', () => {
})
})
})
+
+ it('revalidates the confirmation field when the password changes', async () => {
+ const user = userEvent.setup()
+ renderWithQueryClient(<ChangePasswordForm />)
+
+ const passwordInput = screen.getByLabelText('common.account.newPassword')
+ await user.type(passwordInput, 'ValidPass123!')
+ const confirmPasswordInput = screen.getByLabelText('common.account.confirmPassword')
+ await user.type(confirmPasswordInput, 'DifferentPass123!{Enter}')
+
+ const error = await screen.findByText('common.account.notEqual')
+ expect(confirmPasswordInput).toHaveAttribute('aria-invalid', 'true')
+ expect(confirmPasswordInput).toHaveAccessibleDescription(error.textContent ?? '')
+ expect(confirmPasswordInput).toHaveFocus()
+ expect(mockRegister).not.toHaveBeenCalled()
+
+ await user.clear(passwordInput)
+ await user.type(passwordInput, 'DifferentPass123!')
+
+ await waitFor(() => {
+ expect(screen.queryByText('common.account.notEqual')).not.toBeInTheDocument()
+ })
+ expect(confirmPasswordInput).not.toHaveAttribute('aria-invalid', 'true')
+ expect(mockRegister).not.toHaveBeenCalled()
+ })
})
// On successful registration the Amplitude event is deferred (remembered) so it can
// fire after the user ID is attached, while the GA event still fires immediately.
describe('Registration success tracking', () => {
- const fillAndSubmit = () => {
- fireEvent.change(screen.getByLabelText('common.account.newPassword'), {
- target: { value: 'ValidPass123!' },
- })
- fireEvent.change(screen.getByLabelText('common.account.confirmPassword'), {
- target: { value: 'ValidPass123!' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'login.changePasswordBtn' }))
+ const fillAndSubmit = async () => {
+ const user = userEvent.setup()
+ await user.type(screen.getByLabelText('common.account.newPassword'), 'ValidPass123!')
+ await user.type(screen.getByLabelText('common.account.confirmPassword'), 'ValidPass123!')
+ await user.click(screen.getByRole('button', { name: 'login.changePasswordBtn' }))
}
it('should defer the amplitude event and fire GA immediately when registration succeeds', async () => {
mockRegister.mockResolvedValue({ result: 'success', data: {} })
renderWithQueryClient(<ChangePasswordForm />)
- fillAndSubmit()
+ await fillAndSubmit()
await waitFor(() => {
expect(mockRememberRegistrationSuccess).toHaveBeenCalledWith({
@@ -165,7 +188,7 @@ describe('Signup Set Password Page', () => {
mockRegister.mockResolvedValue({ result: 'success', data: {} })
renderWithQueryClient(<ChangePasswordForm />)
- fillAndSubmit()
+ await fillAndSubmit()
await waitFor(() => {
expect(mockReplace).toHaveBeenCalledWith('/apps?tag=workflow')
@@ -177,7 +200,7 @@ describe('Signup Set Password Page', () => {
mockRegister.mockResolvedValue({ result: 'success', data: {} })
renderWithQueryClient(<ChangePasswordForm />)
- fillAndSubmit()
+ await fillAndSubmit()
await waitFor(() => {
expect(mockRememberRegistrationSuccess).toHaveBeenCalledWith({
diff --git a/web/app/signup/set-password/page.tsx b/web/app/signup/set-password/page.tsx
index c9d9d07992c..b22c556346c 100644
--- a/web/app/signup/set-password/page.tsx
+++ b/web/app/signup/set-password/page.tsx
@@ -1,14 +1,21 @@
'use client'
+import type { FormActions } from '@langgenius/dify-ui/form'
import type { MailRegisterResponse } from '@/service/use-common'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FieldValidity,
+} from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { toast } from '@langgenius/dify-ui/toast'
import { useQueryClient } from '@tanstack/react-query'
import Cookies from 'js-cookie'
-import { useCallback, useState } from 'react'
+import { useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { rememberRegistrationSuccess } from '@/app/components/base/amplitude/registration-tracking'
import { resolvePostLoginRedirect } from '@/app/signin/utils/post-login-redirect'
@@ -24,6 +31,11 @@ import { replaceLoginRedirect } from '@/utils/login-redirect.client'
import { getBrowserTimezone } from '@/utils/timezone'
import { basePath } from '@/utils/var'
+type PasswordFormValues = {
+ password: string
+ confirmPassword: string
+}
+
const parseUtmInfo = () => {
const utmInfoStr = Cookies.get('utm_info')
if (!utmInfoStr) return null
@@ -43,76 +55,51 @@ const ChangePasswordForm = () => {
const token = decodeURIComponent(searchParams.get('token') || '')
const locale = useLocale()
- const [password, setPassword] = useState('')
- const [confirmPassword, setConfirmPassword] = useState('')
+ const formActionsRef = useRef<FormActions>(null)
+ const confirmPasswordRef = useRef<HTMLInputElement>(null)
const { mutateAsync: register, isPending } = useMailRegister()
const pageTitle = t(($) => $.changePassword, { ns: 'login' })
useDocumentTitle(pageTitle)
- const showErrorMessage = useCallback((message: string) => {
- toast.error(message)
- }, [])
-
- const valid = useCallback(() => {
- if (!password.trim()) {
- showErrorMessage(t(($) => $['error.passwordEmpty'], { ns: 'login' }))
- return false
- }
- if (!validPassword.test(password)) {
- showErrorMessage(t(($) => $['error.passwordInvalid'], { ns: 'login' }))
- return false
- }
- if (password !== confirmPassword) {
- showErrorMessage(t(($) => $['account.notEqual'], { ns: 'common' }))
- return false
- }
- return true
- }, [password, confirmPassword, showErrorMessage, t])
-
- const handleSubmit = useCallback(async () => {
- if (!valid()) return
- try {
- const res = await register({
- token,
- new_password: password,
- password_confirm: confirmPassword,
- language: locale,
- timezone: getBrowserTimezone(),
- })
- const { result } = res as MailRegisterResponse
- if (result === 'success') {
- const utmInfo = parseUtmInfo()
- rememberCreateAppExternalAttribution({ utmInfo })
- // Defer the Amplitude event until the user ID is attached. The app context
- // external sync replays it after setUserId runs once the redirect lands on /apps.
- // Firing it here would record it under an anonymous Amplitude profile.
- rememberRegistrationSuccess({ method: 'email', utmInfo })
-
- sendGAEvent(utmInfo ? 'user_registration_success_with_utm' : 'user_registration_success', {
- method: 'email',
- ...utmInfo,
+ const handleSubmit = useCallback(
+ async (formValues: PasswordFormValues) => {
+ if (isPending) return
+ try {
+ const res = await register({
+ token,
+ new_password: formValues.password,
+ password_confirm: formValues.confirmPassword,
+ language: locale,
+ timezone: getBrowserTimezone(),
})
- Cookies.remove('utm_info') // Clean up: remove utm_info cookie
+ const { result } = res as MailRegisterResponse
+ if (result === 'success') {
+ const utmInfo = parseUtmInfo()
+ rememberCreateAppExternalAttribution({ utmInfo })
+ // Defer the Amplitude event until the user ID is attached. The app context
+ // external sync replays it after setUserId runs once the redirect lands on /apps.
+ // Firing it here would record it under an anonymous Amplitude profile.
+ rememberRegistrationSuccess({ method: 'email', utmInfo })
- toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
- await queryClient.resetQueries({ queryKey: consoleQuery.account.profile.get.key() })
- replaceLoginRedirect(resolvePostLoginRedirect(searchParams), router.replace, basePath)
+ sendGAEvent(
+ utmInfo ? 'user_registration_success_with_utm' : 'user_registration_success',
+ {
+ method: 'email',
+ ...utmInfo,
+ },
+ )
+ Cookies.remove('utm_info') // Clean up: remove utm_info cookie
+
+ toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
+ await queryClient.resetQueries({ queryKey: consoleQuery.account.profile.get.key() })
+ replaceLoginRedirect(resolvePostLoginRedirect(searchParams), router.replace, basePath)
+ }
+ } catch (error) {
+ console.error(error)
}
- } catch (error) {
- console.error(error)
- }
- }, [
- password,
- token,
- valid,
- confirmPassword,
- register,
- locale,
- queryClient,
- router,
- searchParams,
- t,
- ])
+ },
+ [token, register, locale, queryClient, router, searchParams, t, isPending],
+ )
return (
<div
@@ -127,42 +114,77 @@ const ChangePasswordForm = () => {
</div>
<div className="mx-auto mt-6 w-full">
- <Form onFormSubmit={() => void handleSubmit()}>
- <Field name="password" className="mb-5">
- <FieldLabel className="py-0 text-[14px] leading-5 font-semibold text-text-secondary">
- {t(($) => $['account.newPassword'], { ns: 'common' })}
- </FieldLabel>
+ <Form<PasswordFormValues>
+ actionsRef={formActionsRef}
+ onFormSubmit={(formValues) => void handleSubmit(formValues)}
+ >
+ <Field
+ name="password"
+ validate={(value) => {
+ const passwordValue = String(value)
+ if (!passwordValue.trim())
+ return t(($) => $['error.passwordEmpty'], { ns: 'login' })
+ return validPassword.test(passwordValue)
+ ? null
+ : t(($) => $['error.passwordInvalid'], { ns: 'login' })
+ }}
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $['account.newPassword'], { ns: 'common' })}</FieldLabel>
<Input
type="password"
+ required
autoComplete="new-password"
spellCheck={false}
- value={password}
- onValueChange={setPassword}
+ onValueChange={() => {
+ if (confirmPasswordRef.current?.value)
+ formActionsRef.current?.validate('confirmPassword')
+ }}
placeholder={t(($) => $.passwordPlaceholder, { ns: 'login' }) || ''}
/>
- <FieldDescription className="py-0 text-text-secondary">
- {t(($) => $['error.passwordInvalid'], { ns: 'login' })}
- </FieldDescription>
+ <FieldValidity>
+ {({ validity }) =>
+ validity.valid !== false ? (
+ <FieldDescription>
+ {t(($) => $['error.passwordInvalid'], { ns: 'login' })}
+ </FieldDescription>
+ ) : null
+ }
+ </FieldValidity>
+ <FieldValidity>
+ {({ validity }) => (
+ <FieldError>
+ {t(
+ ($) =>
+ $[validity.valueMissing ? 'error.passwordEmpty' : 'error.passwordInvalid'],
+ { ns: 'login' },
+ )}
+ </FieldError>
+ )}
+ </FieldValidity>
</Field>
- <Field name="confirmPassword" className="mb-5">
- <FieldLabel className="py-0 text-[14px] leading-5 font-semibold text-text-secondary">
- {t(($) => $['account.confirmPassword'], { ns: 'common' })}
- </FieldLabel>
+ <Field
+ name="confirmPassword"
+ validate={(value, formValues) => {
+ const confirmationValue = String(value)
+ return !confirmationValue || confirmationValue === formValues.password
+ ? null
+ : t(($) => $['account.notEqual'], { ns: 'common' })
+ }}
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $['account.confirmPassword'], { ns: 'common' })}</FieldLabel>
<Input
type="password"
+ required
autoComplete="new-password"
spellCheck={false}
- value={confirmPassword}
- onValueChange={setConfirmPassword}
+ ref={confirmPasswordRef}
placeholder={t(($) => $.confirmPasswordPlaceholder, { ns: 'login' }) || ''}
/>
+ <FieldError>{t(($) => $['account.notEqual'], { ns: 'common' })}</FieldError>
</Field>
- <Button
- type="submit"
- variant="primary"
- className="w-full"
- disabled={isPending || !password || !confirmPassword}
- >
+ <Button type="submit" variant="primary" className="w-full" loading={isPending}>
{t(($) => $.changePasswordBtn, { ns: 'login' })}
</Button>
</Form>