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 install account fields (#40992)

yyhb16a24f084b5
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 569d77074ee..d4ff55d86df 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -5154,11 +5154,6 @@
"count": 7
}
},
- "web/app/install/installForm.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/reset-password/check-code/page.tsx": {
"no-restricted-imports": {
"count": 1
diff --git a/web/app/install/installForm.spec.tsx b/web/app/install/installForm.spec.tsx
index 7d2db250216..32904d60d05 100644
--- a/web/app/install/installForm.spec.tsx
+++ b/web/app/install/installForm.spec.tsx
@@ -1,6 +1,7 @@
import type { ReactElement } from 'react'
import type { InitValidateStatusResponse, SetupStatusResponse } from '@/models/common'
import { fireEvent, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { fetchInitValidateStatus, fetchSetupStatus, login, setup } from '@/service/common'
import { expectLoadingButton } from '@/test/button'
import { renderWithConsoleQuery } from '@/test/console/query-data'
@@ -44,22 +45,85 @@ describe('InstallForm', () => {
it('should render form after loading', async () => {
render(<InstallForm />)
- expect(await screen.findByLabelText('login.email')).toBeInTheDocument()
+ const emailInput = await screen.findByLabelText('login.email')
+ const nameInput = screen.getByLabelText('login.name')
+ const passwordInput = screen.getByLabelText('login.password')
+
+ expect(emailInput).toHaveAttribute('type', 'email')
+ expect(emailInput).toHaveAttribute('autocomplete', 'email')
+ expect(nameInput).toHaveAttribute('autocomplete', 'name')
+ expect(nameInput).toHaveAttribute('maxlength', '30')
+ expect(passwordInput).toHaveAttribute('autocomplete', 'new-password')
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('login.setAdminAccount')
expect(screen.getByRole('button', { name: /login\.installBtn/ })).toBeInTheDocument()
})
- it('should show validation error when required fields are empty', async () => {
+ it('should reveal and hide the password with an accessible action', async () => {
+ const user = userEvent.setup()
render(<InstallForm />)
- await screen.findByLabelText('login.email')
+ const passwordInput = await screen.findByLabelText('login.password')
- fireEvent.click(screen.getByRole('button', { name: /login\.installBtn/ }))
+ await user.click(screen.getByRole('button', { name: 'login.showPassword' }))
+ expect(passwordInput).toHaveAttribute('type', 'text')
+
+ await user.click(screen.getByRole('button', { name: 'login.hidePassword' }))
+ expect(passwordInput).toHaveAttribute('type', 'password')
+ })
+
+ it('should identify required fields only after submission', async () => {
+ const user = userEvent.setup()
+ render(<InstallForm />)
+
+ const emailInput = await screen.findByLabelText('login.email')
+ const nameInput = screen.getByLabelText('login.name')
+ const passwordInput = screen.getByLabelText('login.password')
+
+ expect(screen.queryByText('login.error.emailInValid')).not.toBeInTheDocument()
+ expect(screen.queryByText('login.error.nameEmpty')).not.toBeInTheDocument()
+ expect(screen.getAllByText('login.error.passwordInvalid')).toHaveLength(1)
+ expect(passwordInput).toHaveAccessibleDescription('login.error.passwordInvalid')
+
+ await user.click(screen.getByRole('button', { name: /login\.installBtn/ }))
await waitFor(() => {
expect(screen.getByText('login.error.emailInValid')).toBeInTheDocument()
expect(screen.getByText('login.error.nameEmpty')).toBeInTheDocument()
+ expect(screen.getAllByText('login.error.passwordInvalid')).toHaveLength(1)
})
+ expect(emailInput).toHaveAttribute('aria-invalid', 'true')
+ expect(nameInput).toHaveAttribute('aria-invalid', 'true')
+ expect(passwordInput).toHaveAttribute('aria-invalid', 'true')
+ expect(passwordInput).toHaveAccessibleDescription('login.error.passwordInvalid')
+ expect(mockSetup).not.toHaveBeenCalled()
+ })
+
+ it('should identify an invalid email and focus the field', async () => {
+ const user = userEvent.setup()
+ render(<InstallForm />)
+
+ const emailInput = await screen.findByLabelText('login.email')
+ await user.type(emailInput, 'invalid-email')
+ await user.click(screen.getByRole('button', { name: /login\.installBtn/ }))
+
+ expect(await screen.findByText('login.error.emailInValid')).toBeInTheDocument()
+ expect(emailInput).toHaveAttribute('aria-invalid', 'true')
+ expect(emailInput).toHaveFocus()
+ expect(mockSetup).not.toHaveBeenCalled()
+ })
+
+ it('should enforce the password requirements before submission', async () => {
+ const user = userEvent.setup()
+ render(<InstallForm />)
+
+ await user.type(await screen.findByLabelText('login.email'), '[email protected]')
+ await user.type(screen.getByLabelText('login.name'), 'Admin')
+ const passwordInput = screen.getByLabelText('login.password')
+ await user.type(passwordInput, 'abcdefgh')
+ await user.click(screen.getByRole('button', { name: /login\.installBtn/ }))
+
+ expect(passwordInput).toHaveAttribute('aria-invalid', 'true')
+ expect(passwordInput).toHaveFocus()
expect(mockSetup).not.toHaveBeenCalled()
})
diff --git a/web/app/install/installForm.tsx b/web/app/install/installForm.tsx
index d11a64206b8..738f8a68ac5 100644
--- a/web/app/install/installForm.tsx
+++ b/web/app/install/installForm.tsx
@@ -1,16 +1,23 @@
'use client'
import type { InitValidateStatusResponse, SetupStatusResponse } from '@/models/common'
+import { zPostSetupBody } from '@dify/contracts/api/console/setup/zod.gen'
import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
-import { useStore } from '@tanstack/react-form'
+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 { Input } from '@langgenius/dify-ui/input'
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import { useQueryClient } from '@tanstack/react-query'
import * as React from 'react'
import { useEffect } 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 Input from '@/app/components/base/input'
import { validPassword } from '@/config'
import { LICENSE_LINK } from '@/constants/link'
import useDocumentTitle from '@/hooks/use-document-title'
@@ -21,40 +28,29 @@ import { fetchInitValidateStatus, fetchSetupStatus, login, setup } from '@/servi
import { encryptPassword as encodePassword } from '@/utils/encryption'
import Loading from '../components/base/loading'
-const accountFormSchema = z.object({
- email: z.email('error.emailInValid').min(1, {
- error: 'error.emailInValid',
- }),
- name: z.string().min(1, {
- error: 'error.nameEmpty',
- }),
- password: z
- .string()
- .min(8, {
- error: 'error.passwordLengthInValid',
- })
- .regex(validPassword, 'error.passwordInvalid'),
+const accountFormSchema = zPostSetupBody.pick({ email: true, name: true, password: true }).extend({
+ email: zPostSetupBody.shape.email.pipe(z.email()),
+ name: zPostSetupBody.shape.name.min(1),
+ password: zPostSetupBody.shape.password.min(8).regex(validPassword),
})
+type AccountFormValues = z.infer<typeof accountFormSchema>
+
const InstallForm = () => {
const { t, i18n } = useTranslation()
const pageTitle = t(($) => $.setAdminAccount, { ns: 'login' })
useDocumentTitle(pageTitle)
- const router = useRouter()
+ const { push, replace } = useRouter()
const queryClient = useQueryClient()
const [showPassword, setShowPassword] = React.useState(false)
const [loading, setLoading] = React.useState(true)
+ const [isSubmitting, setIsSubmitting] = React.useState(false)
- const form = useAppForm({
- defaultValues: {
- name: '',
- password: '',
- email: '',
- },
- validators: {
- onSubmit: zodSubmitValidator(accountFormSchema),
- },
- onSubmit: async ({ value }) => {
+ const handleSubmit = async (value: AccountFormValues) => {
+ if (isSubmitting) return
+
+ setIsSubmitting(true)
+ try {
// First, setup the admin account
await setup({
body: {
@@ -75,31 +71,28 @@ const InstallForm = () => {
// Store tokens and redirect if login successful
if (loginRes.result === 'success') {
await queryClient.resetQueries({ queryKey: consoleQuery.account.profile.get.key() })
- router.replace('/')
+ replace('/')
} else {
// Fallback to signin page if auto-login fails
- router.replace('/signin')
+ replace('/signin')
}
- },
- })
-
- const isSubmitting = useStore(form.store, (state) => state.isSubmitting)
- const emailErrors = useStore(form.store, (state) => state.fieldMeta.email?.errors)
- const nameErrors = useStore(form.store, (state) => state.fieldMeta.name?.errors)
- const passwordErrors = useStore(form.store, (state) => state.fieldMeta.password?.errors)
+ } finally {
+ setIsSubmitting(false)
+ }
+ }
useEffect(() => {
fetchSetupStatus().then((res: SetupStatusResponse) => {
if (res.step === 'finished') {
- router.push('/signin')
+ push('/signin')
} else {
fetchInitValidateStatus().then((res: InitValidateStatusResponse) => {
- if (res.status === 'not_started') router.push('/init')
+ if (res.status === 'not_started') push('/init')
})
}
setLoading(false)
})
- }, [])
+ }, [push])
return loading ? (
<Loading />
@@ -113,123 +106,97 @@ const InstallForm = () => {
</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()
- if (isSubmitting) return
- form.handleSubmit()
- }}
+ <Form<AccountFormValues> onFormSubmit={(value) => void handleSubmit(value)}>
+ <Field
+ name="email"
+ validate={(value) =>
+ accountFormSchema.shape.email.safeParse(value).success
+ ? null
+ : t(($) => $['error.emailInValid'], { ns: 'login' })
+ }
+ className="mb-5"
>
- <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>
+ <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>
- <div className="mb-5">
- <label
- htmlFor="name"
- className="my-2 flex items-center justify-between text-sm font-medium text-text-primary"
- >
- {t(($) => $.name, { ns: 'login' })}
- </label>
- <div className="relative mt-1">
- <form.AppField name="name">
- {(field) => (
- <Input
- id="name"
- value={field.state.value}
- onChange={(e) => field.handleChange(e.target.value)}
- onBlur={field.handleBlur}
- placeholder={t(($) => $.namePlaceholder, { ns: 'login' }) || ''}
- />
- )}
- </form.AppField>
- </div>
- {nameErrors && nameErrors.length > 0 && (
- <span className="text-sm text-red-400">
- {t(($) => $[`${nameErrors[0]}` as 'error.nameEmpty'], { ns: 'login' })}
- </span>
- )}
- </div>
-
- <div className="mb-5">
- <label
- htmlFor="password"
- className="my-2 flex items-center justify-between text-sm font-medium text-text-primary"
- >
- {t(($) => $.password, { ns: 'login' })}
- </label>
- <div className="relative mt-1">
- <form.AppField name="password">
- {(field) => (
- <Input
- id="password"
- type={showPassword ? 'text' : 'password'}
- value={field.state.value}
- onChange={(e) => field.handleChange(e.target.value)}
- onBlur={field.handleBlur}
- placeholder={t(($) => $.passwordPlaceholder, { ns: 'login' }) || ''}
- />
- )}
- </form.AppField>
-
- <div className="absolute inset-y-0 right-0 flex items-center pr-3">
- <button
- type="button"
- onClick={() => setShowPassword(!showPassword)}
- className="text-text-quaternary hover:text-text-tertiary focus:text-text-tertiary focus:outline-hidden"
- >
- {showPassword ? '👀' : '😝'}
- </button>
- </div>
- </div>
+ <Field
+ name="name"
+ validate={(value) =>
+ accountFormSchema.shape.name.safeParse(value).success
+ ? null
+ : t(($) => $['error.nameEmpty'], { ns: 'login' })
+ }
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $.name, { ns: 'login' })}</FieldLabel>
+ <Input
+ autoComplete="name"
+ required
+ maxLength={30}
+ placeholder={t(($) => $.namePlaceholder, { ns: 'login' }) || ''}
+ />
+ <FieldError>{t(($) => $['error.nameEmpty'], { ns: 'login' })}</FieldError>
+ </Field>
- <div
- className={cn('mt-1 text-xs text-text-secondary', {
- 'text-sm! text-red-400': passwordErrors && passwordErrors.length > 0,
- })}
- >
- {t(($) => $['error.passwordInvalid'], { ns: 'login' })}
- </div>
- </div>
+ <Field
+ name="password"
+ validate={(value) =>
+ accountFormSchema.shape.password.safeParse(value).success
+ ? null
+ : t(($) => $['error.passwordInvalid'], { ns: 'login' })
+ }
+ className="mb-5"
+ >
+ <FieldLabel>{t(($) => $.password, { ns: 'login' })}</FieldLabel>
+ <InputGroup>
+ <InputGroupInput
+ type={showPassword ? 'text' : 'password'}
+ autoComplete="new-password"
+ spellCheck={false}
+ required
+ minLength={8}
+ placeholder={t(($) => $.passwordPlaceholder, { ns: 'login' }) || ''}
+ />
+ <InputGroupAddon align="inline-end">
+ <IconButton
+ aria-label={t(($) => $[showPassword ? 'hidePassword' : 'showPassword'], {
+ ns: 'login',
+ })}
+ onClick={() => setShowPassword((visible) => !visible)}
+ >
+ <span
+ aria-hidden="true"
+ className={showPassword ? 'i-ri-eye-off-line size-4' : 'i-ri-eye-line size-4'}
+ />
+ </IconButton>
+ </InputGroupAddon>
+ </InputGroup>
+ <FieldValidity>
+ {({ validity }) =>
+ validity.valid === false ? null : (
+ <FieldDescription className="text-text-secondary">
+ {t(($) => $['error.passwordInvalid'], { ns: 'login' })}
+ </FieldDescription>
+ )
+ }
+ </FieldValidity>
+ <FieldError>{t(($) => $['error.passwordInvalid'], { ns: 'login' })}</FieldError>
+ </Field>
- <div>
- <Button
- variant="primary"
- type="submit"
- disabled={isSubmitting}
- loading={isSubmitting}
- className="w-full"
- >
- {t(($) => $.installBtn, { ns: 'login' })}
- </Button>
- </div>
- </form>
- </formContext.Provider>
+ <div>
+ <Button variant="primary" type="submit" loading={isSubmitting} className="w-full">
+ {t(($) => $.installBtn, { ns: 'login' })}
+ </Button>
+ </div>
+ </Form>
<div className="mt-2 block w-full text-xs text-text-secondary">
{t(($) => $['license.tip'], { ns: 'login' })}
&nbsp;