refactor(web): migrate legacy forms to TanStack Form (#30631)

This commit is contained in:
yyh
2026-01-06 20:18:27 +08:00
committed by GitHub
parent 64bfcbc4a9
commit 7beed12eab
9 changed files with 551 additions and 202 deletions

View File

@ -0,0 +1,163 @@
import type { InitValidateStatusResponse, SetupStatusResponse } from '@/models/common'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { fetchInitValidateStatus, fetchSetupStatus, sendForgotPasswordEmail } from '@/service/common'
import ForgotPasswordForm from './ForgotPasswordForm'
const mockPush = vi.fn()
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: mockPush }),
}))
vi.mock('@/service/common', () => ({
fetchSetupStatus: vi.fn(),
fetchInitValidateStatus: vi.fn(),
sendForgotPasswordEmail: vi.fn(),
}))
const mockFetchSetupStatus = vi.mocked(fetchSetupStatus)
const mockFetchInitValidateStatus = vi.mocked(fetchInitValidateStatus)
const mockSendForgotPasswordEmail = vi.mocked(sendForgotPasswordEmail)
const prepareLoadedState = () => {
mockFetchSetupStatus.mockResolvedValue({ step: 'not_started' } as SetupStatusResponse)
mockFetchInitValidateStatus.mockResolvedValue({ status: 'finished' } as InitValidateStatusResponse)
}
describe('ForgotPasswordForm', () => {
beforeEach(() => {
vi.clearAllMocks()
prepareLoadedState()
})
it('should render form after loading', async () => {
render(<ForgotPasswordForm />)
expect(await screen.findByLabelText('login.email')).toBeInTheDocument()
})
it('should show validation error when email is empty', async () => {
render(<ForgotPasswordForm />)
await screen.findByLabelText('login.email')
fireEvent.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
await waitFor(() => {
expect(screen.getByText('login.error.emailInValid')).toBeInTheDocument()
})
expect(mockSendForgotPasswordEmail).not.toHaveBeenCalled()
})
it('should send reset email and navigate after confirmation', async () => {
mockSendForgotPasswordEmail.mockResolvedValue({ result: 'success', data: 'ok' } as any)
render(<ForgotPasswordForm />)
const emailInput = await screen.findByLabelText('login.email')
fireEvent.change(emailInput, { target: { value: 'test@example.com' } })
fireEvent.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
await waitFor(() => {
expect(mockSendForgotPasswordEmail).toHaveBeenCalledWith({
url: '/forgot-password',
body: { email: 'test@example.com' },
})
})
await waitFor(() => {
expect(screen.getByRole('button', { name: /login\.backToSignIn/ })).toBeInTheDocument()
})
fireEvent.click(screen.getByRole('button', { name: /login\.backToSignIn/ }))
expect(mockPush).toHaveBeenCalledWith('/signin')
})
it('should submit when form is submitted', async () => {
mockSendForgotPasswordEmail.mockResolvedValue({ result: 'success', data: 'ok' } as any)
render(<ForgotPasswordForm />)
fireEvent.change(await screen.findByLabelText('login.email'), { target: { value: 'test@example.com' } })
const form = screen.getByRole('button', { name: /login\.sendResetLink/ }).closest('form')
expect(form).not.toBeNull()
fireEvent.submit(form as HTMLFormElement)
await waitFor(() => {
expect(mockSendForgotPasswordEmail).toHaveBeenCalledWith({
url: '/forgot-password',
body: { email: 'test@example.com' },
})
})
})
it('should disable submit while request is in flight', async () => {
let resolveRequest: ((value: any) => void) | undefined
const requestPromise = new Promise((resolve) => {
resolveRequest = resolve
})
mockSendForgotPasswordEmail.mockReturnValue(requestPromise as any)
render(<ForgotPasswordForm />)
fireEvent.change(await screen.findByLabelText('login.email'), { target: { value: 'test@example.com' } })
const button = screen.getByRole('button', { name: /login\.sendResetLink/ })
fireEvent.click(button)
await waitFor(() => {
expect(button).toBeDisabled()
})
fireEvent.click(button)
expect(mockSendForgotPasswordEmail).toHaveBeenCalledTimes(1)
resolveRequest?.({ result: 'success', data: 'ok' })
await waitFor(() => {
expect(screen.getByRole('button', { name: /login\.backToSignIn/ })).toBeInTheDocument()
})
})
it('should keep form state when request fails', async () => {
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: 'test@example.com' } })
fireEvent.click(screen.getByRole('button', { name: /login\.sendResetLink/ }))
await waitFor(() => {
expect(mockSendForgotPasswordEmail).toHaveBeenCalledTimes(1)
})
expect(screen.getByRole('button', { name: /login\.sendResetLink/ })).toBeInTheDocument()
expect(mockPush).not.toHaveBeenCalled()
consoleSpy.mockRestore()
})
it('should redirect to init when status is not started', async () => {
const originalLocation = window.location
Object.defineProperty(window, 'location', {
value: { href: '' },
writable: true,
})
mockFetchInitValidateStatus.mockResolvedValue({ status: 'not_started' } as InitValidateStatusResponse)
render(<ForgotPasswordForm />)
await waitFor(() => {
expect(window.location.href).toBe('/init')
})
Object.defineProperty(window, 'location', {
value: originalLocation,
writable: true,
})
})
})

View File

@ -1,15 +1,16 @@
'use client'
import type { InitValidateStatusResponse } from '@/models/common'
import { zodResolver } from '@hookform/resolvers/zod'
import { useStore } from '@tanstack/react-form'
import { useRouter } from 'next/navigation'
import * as React from 'react'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod'
import Button from '@/app/components/base/button'
import { formContext, useAppForm } from '@/app/components/base/form'
import { zodSubmitValidator } from '@/app/components/base/form/utils/zod-submit-validator'
import {
fetchInitValidateStatus,
fetchSetupStatus,
@ -27,44 +28,45 @@ const accountFormSchema = z.object({
.email('error.emailInValid'),
})
type AccountFormValues = z.infer<typeof accountFormSchema>
const ForgotPasswordForm = () => {
const { t } = useTranslation()
const router = useRouter()
const [loading, setLoading] = useState(true)
const [isEmailSent, setIsEmailSent] = useState(false)
const { register, trigger, getValues, formState: { errors } } = useForm<AccountFormValues>({
resolver: zodResolver(accountFormSchema),
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 handleSendResetPasswordEmail = async (email: string) => {
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)
}
}
const isSubmitting = useStore(form.store, state => state.isSubmitting)
const emailErrors = useStore(form.store, state => state.fieldMeta.email?.errors)
const handleSendResetPasswordClick = async () => {
if (isSubmitting)
return
if (isEmailSent) {
router.push('/signin')
}
else {
const isValid = await trigger('email')
if (isValid) {
const email = getValues('email')
await handleSendResetPasswordEmail(email)
}
form.handleSubmit()
}
}
@ -94,30 +96,51 @@ const ForgotPasswordForm = () => {
</div>
<div className="mt-8 grow sm:mx-auto sm:w-full sm:max-w-md">
<div className="relative">
<form>
{!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">
<Input
{...register('email')}
placeholder={t('emailPlaceholder', { ns: 'login' }) || ''}
/>
{errors.email && <span className="text-sm text-red-400">{t(`${errors.email?.message}` as 'error.emailInValid', { ns: 'login' })}</span>}
<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>
<Button variant="primary" className="w-full" disabled={isSubmitting} onClick={handleSendResetPasswordClick}>
{isEmailSent ? t('backToSignIn', { ns: 'login' }) : t('sendResetLink', { ns: 'login' })}
</Button>
</div>
)}
<div>
<Button variant="primary" className="w-full" onClick={handleSendResetPasswordClick}>
{isEmailSent ? t('backToSignIn', { ns: 'login' }) : t('sendResetLink', { ns: 'login' })}
</Button>
</div>
</form>
</form>
</formContext.Provider>
</div>
</div>
</>