|
| 1 | +import { zodResolver } from '@hookform/resolvers/zod'; |
| 2 | +import { PasswordField } from '@lambdacurry/forms/remix-hook-form/password-field'; |
| 3 | +import { Button } from '@lambdacurry/forms/ui/button'; |
| 4 | +import type { Meta, StoryContext, StoryObj } from '@storybook/react-vite'; |
| 5 | +import { expect, userEvent } from '@storybook/test'; |
| 6 | +import { useRef } from 'react'; |
| 7 | +import { type ActionFunctionArgs, useFetcher } from 'react-router'; |
| 8 | +import { RemixFormProvider, getValidatedFormData, useRemixForm } from 'remix-hook-form'; |
| 9 | +import { z } from 'zod'; |
| 10 | +import { withReactRouterStubDecorator } from '../lib/storybook/react-router-stub'; |
| 11 | + |
| 12 | +const formSchema = z |
| 13 | + .object({ |
| 14 | + password: z.string().min(8, 'Password must be at least 8 characters'), |
| 15 | + confirmPassword: z.string().min(1, 'Please confirm your password'), |
| 16 | + }) |
| 17 | + .refine((data) => data.password === data.confirmPassword, { |
| 18 | + message: "Passwords don't match", |
| 19 | + path: ['confirmPassword'], |
| 20 | + }); |
| 21 | + |
| 22 | +type FormData = z.infer<typeof formSchema>; |
| 23 | + |
| 24 | +const INITIAL_PASSWORD = 'test123456'; |
| 25 | +const WEAK_PASSWORD = '123'; |
| 26 | +const WEAK_PASSWORD_ERROR = 'Password must be at least 8 characters'; |
| 27 | +const MISMATCH_PASSWORD_ERROR = "Passwords don't match"; |
| 28 | + |
| 29 | +const CreateAccountForm = () => { |
| 30 | + const fetcher = useFetcher<{ message: string; success: boolean }>(); |
| 31 | + const methods = useRemixForm<FormData>({ |
| 32 | + resolver: zodResolver(formSchema), |
| 33 | + defaultValues: { |
| 34 | + password: INITIAL_PASSWORD, |
| 35 | + confirmPassword: INITIAL_PASSWORD, |
| 36 | + }, |
| 37 | + fetcher, |
| 38 | + submitConfig: { |
| 39 | + action: '/', |
| 40 | + method: 'post', |
| 41 | + }, |
| 42 | + }); |
| 43 | + |
| 44 | + const ref = useRef<HTMLInputElement>(null); |
| 45 | + |
| 46 | + return ( |
| 47 | + <RemixFormProvider {...methods}> |
| 48 | + <fetcher.Form onSubmit={methods.handleSubmit}> |
| 49 | + <div className="space-y-6 max-w-md"> |
| 50 | + <div className="text-center mb-6"> |
| 51 | + <h2 className="text-2xl font-bold text-gray-900">Create Account</h2> |
| 52 | + <p className="text-gray-600 mt-2">Enter your password details to get started</p> |
| 53 | + </div> |
| 54 | + |
| 55 | + <PasswordField |
| 56 | + name="password" |
| 57 | + label="Password" |
| 58 | + description="Must be at least 8 characters long" |
| 59 | + placeholder="Enter your password" |
| 60 | + /> |
| 61 | + |
| 62 | + <PasswordField |
| 63 | + name="confirmPassword" |
| 64 | + label="Confirm Password" |
| 65 | + description="Re-enter your password to confirm" |
| 66 | + placeholder="Confirm your password" |
| 67 | + /> |
| 68 | + |
| 69 | + <div className="flex gap-2 items-end"> |
| 70 | + <PasswordField name="refExample" label="Ref Example" placeholder="This field has a ref" ref={ref} /> |
| 71 | + <Button type="button" onClick={() => ref.current?.focus()}> |
| 72 | + Focus |
| 73 | + </Button> |
| 74 | + </div> |
| 75 | + |
| 76 | + <Button type="submit" className="w-full mt-6"> |
| 77 | + Create Account |
| 78 | + </Button> |
| 79 | + |
| 80 | + {fetcher.data?.message && ( |
| 81 | + <p className={`mt-2 text-center ${fetcher.data.success ? 'text-green-600' : 'text-red-600'}`}> |
| 82 | + {fetcher.data.message} |
| 83 | + </p> |
| 84 | + )} |
| 85 | + </div> |
| 86 | + </fetcher.Form> |
| 87 | + </RemixFormProvider> |
| 88 | + ); |
| 89 | +}; |
| 90 | + |
| 91 | +const handleFormSubmission = async (request: Request) => { |
| 92 | + const { data, errors } = await getValidatedFormData<FormData>(request, zodResolver(formSchema)); |
| 93 | + |
| 94 | + if (errors) { |
| 95 | + return { errors }; |
| 96 | + } |
| 97 | + |
| 98 | + // Simulate account creation - data is validated at this point |
| 99 | + console.log('Creating account with password length:', data.password.length); |
| 100 | + return { |
| 101 | + message: 'Account created successfully! Welcome aboard!', |
| 102 | + success: true, |
| 103 | + }; |
| 104 | +}; |
| 105 | + |
| 106 | +const meta: Meta<typeof PasswordField> = { |
| 107 | + title: 'RemixHookForm/PasswordField', |
| 108 | + component: PasswordField, |
| 109 | + parameters: { layout: 'centered' }, |
| 110 | + tags: ['autodocs'], |
| 111 | +}; |
| 112 | + |
| 113 | +export default meta; |
| 114 | +type Story = StoryObj<typeof meta>; |
| 115 | + |
| 116 | +// Test scenarios |
| 117 | +const testDefaultValues = ({ canvas }: StoryContext) => { |
| 118 | + const passwordInput = canvas.getByLabelText('Password'); |
| 119 | + const confirmInput = canvas.getByLabelText('Confirm Password'); |
| 120 | + expect(passwordInput).toHaveValue(INITIAL_PASSWORD); |
| 121 | + expect(confirmInput).toHaveValue(INITIAL_PASSWORD); |
| 122 | +}; |
| 123 | + |
| 124 | +const testPasswordVisibilityToggle = async ({ canvas }: StoryContext) => { |
| 125 | + const passwordInput = canvas.getByLabelText('Password'); |
| 126 | + |
| 127 | + // Find the toggle button within the same form item as the password input |
| 128 | + const formItem = |
| 129 | + passwordInput.closest('[class*="FormItem"], .form-item, [data-testid="form-item"]') || |
| 130 | + passwordInput.parentElement?.parentElement; |
| 131 | + const toggleButton = formItem?.querySelector('button[aria-label="Show password"]') as HTMLElement; |
| 132 | + |
| 133 | + // Initially password should be hidden (type="password") |
| 134 | + expect(passwordInput).toHaveAttribute('type', 'password'); |
| 135 | + |
| 136 | + // Click toggle to show password |
| 137 | + await userEvent.click(toggleButton); |
| 138 | + expect(passwordInput).toHaveAttribute('type', 'text'); |
| 139 | + |
| 140 | + // Find the hide button for the same field |
| 141 | + const hideButton = formItem?.querySelector('button[aria-label="Hide password"]') as HTMLElement; |
| 142 | + expect(hideButton).toBeInTheDocument(); |
| 143 | + |
| 144 | + // Click toggle to hide password again |
| 145 | + await userEvent.click(hideButton); |
| 146 | + expect(passwordInput).toHaveAttribute('type', 'password'); |
| 147 | + |
| 148 | + // Verify show button is back |
| 149 | + const showButtonAgain = formItem?.querySelector('button[aria-label="Show password"]') as HTMLElement; |
| 150 | + expect(showButtonAgain).toBeInTheDocument(); |
| 151 | +}; |
| 152 | + |
| 153 | +const testWeakPasswordValidation = async ({ canvas }: StoryContext) => { |
| 154 | + const passwordInput = canvas.getByLabelText('Password'); |
| 155 | + const submitButton = canvas.getByRole('button', { name: 'Create Account' }); |
| 156 | + |
| 157 | + await userEvent.click(passwordInput); |
| 158 | + await userEvent.clear(passwordInput); |
| 159 | + await userEvent.type(passwordInput, WEAK_PASSWORD); |
| 160 | + await userEvent.click(submitButton); |
| 161 | + |
| 162 | + await expect(await canvas.findByText(WEAK_PASSWORD_ERROR)).toBeInTheDocument(); |
| 163 | +}; |
| 164 | + |
| 165 | +const testPasswordMismatchValidation = async ({ canvas }: StoryContext) => { |
| 166 | + const passwordInput = canvas.getByLabelText('Password'); |
| 167 | + const confirmInput = canvas.getByLabelText('Confirm Password'); |
| 168 | + const submitButton = canvas.getByRole('button', { name: 'Create Account' }); |
| 169 | + |
| 170 | + await userEvent.click(passwordInput); |
| 171 | + await userEvent.clear(passwordInput); |
| 172 | + await userEvent.type(passwordInput, 'validpassword123'); |
| 173 | + |
| 174 | + await userEvent.click(confirmInput); |
| 175 | + await userEvent.clear(confirmInput); |
| 176 | + await userEvent.type(confirmInput, 'differentpassword123'); |
| 177 | + |
| 178 | + await userEvent.click(submitButton); |
| 179 | + |
| 180 | + await expect(await canvas.findByText(MISMATCH_PASSWORD_ERROR)).toBeInTheDocument(); |
| 181 | +}; |
| 182 | + |
| 183 | +const testValidSubmission = async ({ canvas }: StoryContext) => { |
| 184 | + const passwordInput = canvas.getByLabelText('Password'); |
| 185 | + const confirmInput = canvas.getByLabelText('Confirm Password'); |
| 186 | + const submitButton = canvas.getByRole('button', { name: 'Create Account' }); |
| 187 | + |
| 188 | + await userEvent.click(passwordInput); |
| 189 | + await userEvent.clear(passwordInput); |
| 190 | + await userEvent.type(passwordInput, 'validpassword123'); |
| 191 | + |
| 192 | + await userEvent.click(confirmInput); |
| 193 | + await userEvent.clear(confirmInput); |
| 194 | + await userEvent.type(confirmInput, 'validpassword123'); |
| 195 | + |
| 196 | + await userEvent.click(submitButton); |
| 197 | + |
| 198 | + const successMessage = await canvas.findByText('Account created successfully! Welcome aboard!'); |
| 199 | + expect(successMessage).toBeInTheDocument(); |
| 200 | +}; |
| 201 | + |
| 202 | +const testRefFunctionality = async ({ canvas }: StoryContext) => { |
| 203 | + const refInput = canvas.getByLabelText('Ref Example'); |
| 204 | + const focusButton = canvas.getByRole('button', { name: 'Focus' }); |
| 205 | + |
| 206 | + await userEvent.click(focusButton); |
| 207 | + expect(refInput).toHaveFocus(); |
| 208 | +}; |
| 209 | + |
| 210 | +// Single story that contains all variants and tests |
| 211 | +export const CreateAccountExample: Story = { |
| 212 | + play: async (storyContext) => { |
| 213 | + testDefaultValues(storyContext); |
| 214 | + await testPasswordVisibilityToggle(storyContext); |
| 215 | + await testWeakPasswordValidation(storyContext); |
| 216 | + await testPasswordMismatchValidation(storyContext); |
| 217 | + await testValidSubmission(storyContext); |
| 218 | + await testRefFunctionality(storyContext); |
| 219 | + }, |
| 220 | + decorators: [ |
| 221 | + withReactRouterStubDecorator({ |
| 222 | + routes: [ |
| 223 | + { |
| 224 | + path: '/', |
| 225 | + Component: CreateAccountForm, |
| 226 | + action: async ({ request }: ActionFunctionArgs) => handleFormSubmission(request), |
| 227 | + }, |
| 228 | + ], |
| 229 | + }), |
| 230 | + ], |
| 231 | +}; |
0 commit comments