| 1 | "use client"; |
| 2 | |
| 3 | import { |
| 4 | type AdditionalField as AdditionalFieldConfig |
| 5 | type AdditionalFieldFormValue, |
| 6 | DEFAULT_ADDITIONAL_FIELD_VALIDATION_DEBOUNCE_MS, |
| 7 | getFormFieldErrors, |
| 8 | normalizeAuthFormServerError, |
| 9 | validateAdditionalFieldRequired, |
| 10 | validateAdditionalFieldValue, |
| 11 | validateStringLength, |
| 12 | } from "@better-auth-ui/core"; |
| 13 | import { useAuth } |
| 14 | import { |
| 15 | type AnyFormApi, |
| 16 | createFormHook, |
| 17 | createFormHookContexts, |
| 18 | } from "@tanstack/react-form"; |
| 19 | import { Eye, EyeOff |
| 20 | import { |
| 21 | type ComponentProps, |
| 22 | type FormEvent, |
| 23 | type ReactNode, |
| 24 | useRef, |
| 25 | useState, |
| 26 | } from "react"; |
| 27 | |
| 28 | import { Button } |
| 29 | import { |
| 30 | Field, |
| 31 | FieldDescription, |
| 32 | FieldError, |
| 33 | FieldLabel, |
| 34 | } from "@/components/ui/field"; |
| 35 | import { Input } |
| 36 | import { |
| 37 | InputGroup, |
| 38 | InputGroupAddon, |
| 39 | InputGroupButton, |
| 40 | InputGroupInput, |
| 41 | } from "@/components/ui/input-group"; |
| 42 | import { Skeleton } |
| 43 | import { Spinner } |
| 44 | import { AdditionalField, type |
| 45 | |
| 46 | const { fieldContext, |
| 47 | createFormHookContexts(); |
| 48 | |
| 49 | const DEFAULT_AUTH_FORM_SERVER_ERROR = " |
| 50 | |
| 51 | function focusFirstInvalidAuthFormControl(form |
| 52 | requestAnimationFrame(() => |
| 53 | form |
| 54 | .querySelector<HTMLElement |
| 55 | '[aria-invalid="true"]:not([disabled]), :invalid:not([disabled])', |
| 56 | ) |
| 57 | ?.focus(); |
| 58 | }); |
| 59 | } |
| 60 | |
| 61 | function AuthFormFieldError() { |
| 62 | const field = |
| 63 | const isInvalid = |
| 64 | |
| 65 | if (!isInvalid) |
| 66 | |
| 67 | const errors = |
| 68 | |
| 69 | return errors.length |
| 70 | } |
| 71 | |
| 72 | function setAuthFormServerError( |
| 73 | form: AnyFormApi |
| 74 | error: unknown, |
| 75 | fallbackMessage: string, |
| 76 | ) { |
| 77 | const normalized = |
| 78 | form.setErrorMap({ |
| 79 | onServer: { |
| 80 | fields: normalized.fields |
| 81 | form: normalized.form |
| 82 | }, |
| 83 | }); |
| 84 | } |
| 85 | |
| 86 | function clearAuthFormServerError(form: |
| 87 | form.setErrorMap({ |
| 88 | } |
| 89 | |
| 90 | function clearAuthFormFieldServerError(form: |
| 91 | form.setErrorMap({ |
| 92 | if (!fieldName) |
| 93 | |
| 94 | const fieldMeta = |
| 95 | if (!fieldMeta?.errorMap |
| 96 | |
| 97 | form.setFieldMeta(fieldName |
| 98 | ...current, |
| 99 | errorMap: { ...current |
| 100 | errorSourceMap: { ...current |
| 101 | })); |
| 102 | } |
| 103 | |
| 104 | async function submitAuthForm( |
| 105 | clearAuthFormServerError(form); |
| 106 | try { |
| 107 | await form.handleSubmit |
| 108 | return form.state |
| 109 | } catch (error) |
| 110 | if (!form.state |
| 111 | setAuthFormServerError(form, error |
| 112 | } |
| 113 | return false; |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | type AuthFormRootProps |
| 118 | onBeforeSubmit?: () |
| 119 | }; |
| 120 | |
| 121 | function AuthFormRoot({ |
| 122 | children, |
| 123 | onBeforeSubmit, |
| 124 | onInput, |
| 125 | ...props |
| 126 | }: AuthFormRootProps) |
| 127 | const form = |
| 128 | const submittingRef = |
| 129 | |
| 130 | async function submit |
| 131 | event.preventDefault(); |
| 132 | if (submittingRef.current |
| 133 | |
| 134 | const formElement = |
| 135 | onBeforeSubmit?.(); |
| 136 | submittingRef.current = |
| 137 | try { |
| 138 | const isValid = |
| 139 | if (!isValid) |
| 140 | } finally { |
| 141 | submittingRef.current = |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | return ( |
| 146 | <form |
| 147 | {...props} |
| 148 | onInvalid={(event) |
| 149 | focusFirstInvalidAuthFormControl(event.currentTarget |
| 150 | } |
| 151 | onInput={(event) |
| 152 | const target = |
| 153 | const fieldName = |
| 154 | target instanceof HTMLInputElement |
| 155 | target instanceof HTMLSelectElement |
| 156 | target instanceof HTMLTextAreaElement |
| 157 | ? target.name |
| 158 | : ""; |
| 159 | clearAuthFormFieldServerError(form, fieldName |
| 160 | onInput?.(event); |
| 161 | }} |
| 162 | onSubmit={submit} |
| 163 | > |
| 164 | {children} |
| 165 | </form> |
| 166 | ); |
| 167 | } |
| 168 | |
| 169 | type AuthFormTextFieldProps |
| 170 | ComponentProps<typeof |
| 171 | "name" | |
| 172 | > & { |
| 173 | description?: ReactNode |
| 174 | label: ReactNode |
| 175 | /** Shows a skeleton in place of the input while what the form acts on loads. */ |
| 176 | isLoading?: boolean |
| 177 | }; |
| 178 | |
| 179 | function AuthFormTextField({ |
| 180 | description, |
| 181 | id, |
| 182 | isLoading, |
| 183 | label, |
| 184 | ...props |
| 185 | }: AuthFormTextFieldProps) |
| 186 | const field = |
| 187 | const form = |
| 188 | const isInvalid = |
| 189 | const inputId = |
| 190 | |
| 191 | return ( |
| 192 | <Field data-invalid={ |
| 193 | <FieldLabel htmlFor={ |
| 194 | {isLoading ? ( |
| 195 | <Skeleton> |
| 196 | <Input className=" |
| 197 | </Skeleton> |
| 198 | ) : ( |
| 199 | <Input |
| 200 | {...props} |
| 201 | aria-busy={field.state |
| 202 | aria-invalid={isInvalid} |
| 203 | id={inputId} |
| 204 | name={field.name |
| 205 | onBlur={field.handleBlur |
| 206 | onChange={(event) |
| 207 | clearAuthFormFieldServerError(form, field |
| 208 | field.handleChange(event |
| 209 | }} |
| 210 | value={field.state |
| 211 | /> |
| 212 | )} |
| 213 | {description ? <FieldDescription |
| 214 | <AuthFormFieldError /> |
| 215 | </Field> |
| 216 | ); |
| 217 | } |
| 218 | |
| 219 | type AuthFormPasswordFieldProps |
| 220 | label: ReactNode |
| 221 | autoComplete: string |
| 222 | placeholder?: string |
| 223 | disabled?: boolean |
| 224 | /** Shows a skeleton in place of the input while what the form acts on loads. */ |
| 225 | isLoading?: boolean |
| 226 | /** Replaces the field's own errors with the breach verdict the haveIBeenPwned plugin returns. */ |
| 227 | isCompromised?: boolean |
| 228 | onValueChange?: () |
| 229 | children?: ReactNode |
| 230 | }; |
| 231 | |
| 232 | function AuthFormPasswordField({ |
| 233 | label, |
| 234 | autoComplete, |
| 235 | placeholder, |
| 236 | disabled, |
| 237 | isLoading, |
| 238 | isCompromised, |
| 239 | onValueChange, |
| 240 | children, |
| 241 | }: AuthFormPasswordFieldProps) |
| 242 | const field = |
| 243 | const form = |
| 244 | const { localization |
| 245 | const [isVisible, |
| 246 | const isInvalid = |
| 247 | const toggleLabel = |
| 248 | ? localization.auth. |
| 249 | : localization.auth. |
| 250 | |
| 251 | return ( |
| 252 | <Field data-invalid={ |
| 253 | <FieldLabel htmlFor={ |
| 254 | {isLoading ? ( |
| 255 | <Skeleton> |
| 256 | <Input className=" |
| 257 | </Skeleton> |
| 258 | ) : ( |
| 259 | <InputGroup> |
| 260 | <InputGroupInput |
| 261 | id={field.name |
| 262 | name={field.name |
| 263 | type={isVisible ? |
| 264 | autoComplete={autoComplete} |
| 265 | value={field.state |
| 266 | onBlur={field.handleBlur |
| 267 | onChange={(event) |
| 268 | clearAuthFormFieldServerError(form, field |
| 269 | field.handleChange(event |
| 270 | onValueChange?.(); |
| 271 | }} |
| 272 | placeholder={placeholder ?? |
| 273 | required |
| 274 | disabled={disabled} |
| 275 | aria-invalid={isInvalid} |
| 276 | /> |
| 277 | <InputGroupAddon align=" |
| 278 | <InputGroupButton |
| 279 | size="icon-xs" |
| 280 | aria-label={toggleLabel} |
| 281 | title={toggleLabel} |
| 282 | onClick={() => |
| 283 | > |
| 284 | {isVisible ? <EyeOff |
| 285 | </InputGroupButton> |
| 286 | </InputGroupAddon> |
| 287 | </InputGroup> |
| 288 | )} |
| 289 | {isCompromised ? ( |
| 290 | <FieldError>{localization. |
| 291 | ) : ( |
| 292 | <AuthFormFieldError /> |
| 293 | )} |
| 294 | {children} |
| 295 | </Field> |
| 296 | ); |
| 297 | } |
| 298 | |
| 299 | export function usePasswordValidator() |
| 300 | const { emailAndPassword, |
| 301 | const { minPasswordLength, |
| 302 | |
| 303 | return ({ value |
| 304 | validateStringLength(value, { |
| 305 | maxLength: maxPasswordLength, |
| 306 | maxLengthMessage: localization.auth |
| 307 | "{{max}}", |
| 308 | String(maxPasswordLength), |
| 309 | ), |
| 310 | minLength: minPasswordLength, |
| 311 | minLengthMessage: localization.auth |
| 312 | "{{min}}", |
| 313 | String(minPasswordLength), |
| 314 | ), |
| 315 | requiredMessage: localization.auth |
| 316 | }); |
| 317 | } |
| 318 | |
| 319 | function AuthFormSubmitButton({ |
| 320 | children, |
| 321 | disabled, |
| 322 | isPending, |
| 323 | ...props |
| 324 | }: ComponentProps< |
| 325 | const form = |
| 326 | |
| 327 | return ( |
| 328 | <form.Subscribe |
| 329 | selector={(state) |
| 330 | > |
| 331 | {([isSubmitting, isValidating |
| 332 | <Button |
| 333 | {...props} |
| 334 | aria-busy={isPending || |
| 335 | aria-disabled={ |
| 336 | disabled || isPending |
| 337 | } |
| 338 | disabled={disabled || |
| 339 | type="submit" |
| 340 | > |
| 341 | {isPending || isSubmitting |
| 342 | <Spinner data-icon=" |
| 343 | ) : null} |
| 344 | {children} |
| 345 | </Button> |
| 346 | )} |
| 347 | </form.Subscribe> |
| 348 | ); |
| 349 | } |
| 350 | |
| 351 | type AuthFormAdditionalFieldProps |
| 352 | AdditionalFieldProps, |
| 353 | "errors" | |
| 354 | >; |
| 355 | |
| 356 | function AuthFormAdditionalField(props: |
| 357 | const field = |
| 358 | const form = |
| 359 | const isInvalid = |
| 360 | |
| 361 | return ( |
| 362 | <AdditionalField |
| 363 | {...props} |
| 364 | errors={ |
| 365 | isInvalid ? getFormFieldErrors( |
| 366 | } |
| 367 | isInvalid={isInvalid} |
| 368 | name={field.name |
| 369 | onBlur={field.handleBlur |
| 370 | onChange={(value) |
| 371 | clearAuthFormFieldServerError(form, field |
| 372 | field.handleChange(value |
| 373 | }} |
| 374 | value={field.state |
| 375 | /> |
| 376 | ); |
| 377 | } |
| 378 | |
| 379 | export const { useAppForm |
| 380 | fieldComponents: { |
| 381 | AuthFormAdditionalField, |
| 382 | AuthFormFieldError, |
| 383 | AuthFormPasswordField, |
| 384 | AuthFormTextField, |
| 385 | }, |
| 386 | fieldContext, |
| 387 | formComponents: { |
| 388 | AuthFormRoot, |
| 389 | AuthFormSubmitButton, |
| 390 | }, |
| 391 | formContext, |
| 392 | }); |
| 393 | |
| 394 | export function isAuthFormFieldInvalid({ |
| 395 | isTouched, |
| 396 | isValid, |
| 397 | }: { |
| 398 | isTouched: boolean |
| 399 | isValid: boolean |
| 400 | }) { |
| 401 | return isTouched && |
| 402 | } |
| 403 | |
| 404 | export function getAuthAdditionalFieldValidators( |
| 405 | field: AdditionalFieldConfig |
| 406 | requiredMessage: string, |
| 407 | ) { |
| 408 | return { |
| 409 | onChange: ({ value |
| 410 | validateAdditionalFieldRequired(field, value |
| 411 | onChangeAsync: field.validate |
| 412 | ? ({ value |
| 413 | validateAdditionalFieldValue(field, value |
| 414 | : undefined, |
| 415 | onChangeAsyncDebounceMs: field.validate |
| 416 | ? (field.validateDebounceMs |
| 417 | DEFAULT_ADDITIONAL_FIELD_VALIDATION_DEBOUNCE_MS) |
| 418 | : undefined, |
| 419 | }; |
| 420 | } |