| 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 | } from "@better-auth-ui/core"; |
| 12 | import { |
| 13 | type AnyFormApi, |
| 14 | createFormHook, |
| 15 | createFormHookContexts, |
| 16 | } from "@tanstack/react-form"; |
| 17 | import { |
| 18 | type ComponentProps, |
| 19 | type FormEvent, |
| 20 | type ReactNode, |
| 21 | useRef, |
| 22 | } from "react"; |
| 23 | |
| 24 | import { Button } |
| 25 | import { |
| 26 | Field, |
| 27 | FieldDescription, |
| 28 | FieldError, |
| 29 | FieldLabel, |
| 30 | } from "@/components/ui/field"; |
| 31 | import { Input } |
| 32 | import { Spinner } |
| 33 | import { AdditionalField, type |
| 34 | |
| 35 | const { fieldContext, |
| 36 | createFormHookContexts(); |
| 37 | |
| 38 | const DEFAULT_AUTH_FORM_SERVER_ERROR = " |
| 39 | |
| 40 | export function focusFirstInvalidAuthFormControl(form |
| 41 | requestAnimationFrame(() => |
| 42 | form |
| 43 | .querySelector<HTMLElement |
| 44 | '[aria-invalid="true"]:not([disabled]), :invalid:not([disabled])', |
| 45 | ) |
| 46 | ?.focus(); |
| 47 | }); |
| 48 | } |
| 49 | |
| 50 | function AuthFormFieldError() { |
| 51 | const field = |
| 52 | const isInvalid = |
| 53 | |
| 54 | if (!isInvalid) |
| 55 | |
| 56 | const errors = |
| 57 | |
| 58 | return errors.length |
| 59 | } |
| 60 | |
| 61 | function AuthFormServerError() { |
| 62 | const form = |
| 63 | |
| 64 | return ( |
| 65 | <form.Subscribe selector={ |
| 66 | {(error) => |
| 67 | const formError = |
| 68 | error && typeof error |
| 69 | ? error.form |
| 70 | : error; |
| 71 | const errors = |
| 72 | return errors.length |
| 73 | }} |
| 74 | </form.Subscribe> |
| 75 | ); |
| 76 | } |
| 77 | |
| 78 | export function setAuthFormServerError( |
| 79 | form: AnyFormApi |
| 80 | error: unknown, |
| 81 | fallbackMessage: string, |
| 82 | ) { |
| 83 | const normalized = |
| 84 | form.setErrorMap({ |
| 85 | onServer: { |
| 86 | fields: normalized.fields |
| 87 | form: normalized.form |
| 88 | }, |
| 89 | }); |
| 90 | } |
| 91 | |
| 92 | export function clearAuthFormServerError(form |
| 93 | form.setErrorMap({ |
| 94 | } |
| 95 | |
| 96 | export function clearAuthFormFieldServerError( |
| 97 | form: AnyFormApi |
| 98 | fieldName: string, |
| 99 | ) { |
| 100 | form.setErrorMap({ |
| 101 | if (!fieldName) |
| 102 | |
| 103 | const fieldMeta = |
| 104 | if (!fieldMeta?.errorMap |
| 105 | |
| 106 | form.setFieldMeta(fieldName |
| 107 | ...current, |
| 108 | errorMap: { ...current |
| 109 | errorSourceMap: { ...current |
| 110 | })); |
| 111 | } |
| 112 | |
| 113 | export async function runAuthFormAction |
| 114 | form: AnyFormApi |
| 115 | action: () |
| 116 | serverErrorMessage = DEFAULT_AUTH_FORM_SERVER_ERROR, |
| 117 | ) { |
| 118 | clearAuthFormServerError(form); |
| 119 | try { |
| 120 | await action(); |
| 121 | return true; |
| 122 | } catch (error) |
| 123 | if (!form.state |
| 124 | setAuthFormServerError(form, error |
| 125 | } |
| 126 | return false; |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | export async function submitAuthForm |
| 131 | form: AnyFormApi |
| 132 | serverErrorMessage = DEFAULT_AUTH_FORM_SERVER_ERROR, |
| 133 | ) { |
| 134 | clearAuthFormServerError(form); |
| 135 | try { |
| 136 | await form.handleSubmit |
| 137 | return form.state |
| 138 | } catch (error) |
| 139 | if (!form.state |
| 140 | setAuthFormServerError(form, error |
| 141 | } |
| 142 | return false; |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | type AuthFormRootProps |
| 147 | onBeforeSubmit?: () |
| 148 | serverErrorMessage?: string |
| 149 | }; |
| 150 | |
| 151 | function AuthFormRoot({ |
| 152 | children, |
| 153 | onBeforeSubmit, |
| 154 | onInput, |
| 155 | serverErrorMessage = DEFAULT_AUTH_FORM_SERVER_ERROR, |
| 156 | ...props |
| 157 | }: AuthFormRootProps) |
| 158 | const form = |
| 159 | const submittingRef = |
| 160 | |
| 161 | async function submit |
| 162 | event.preventDefault(); |
| 163 | if (submittingRef.current |
| 164 | |
| 165 | const formElement = |
| 166 | onBeforeSubmit?.(); |
| 167 | submittingRef.current = |
| 168 | try { |
| 169 | const isValid = |
| 170 | if (!isValid) |
| 171 | } finally { |
| 172 | submittingRef.current = |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | return ( |
| 177 | <form |
| 178 | {...props} |
| 179 | onInvalid={(event) |
| 180 | focusFirstInvalidAuthFormControl(event.currentTarget |
| 181 | } |
| 182 | onInput={(event) |
| 183 | const target = |
| 184 | const fieldName = |
| 185 | target instanceof HTMLInputElement |
| 186 | target instanceof HTMLSelectElement |
| 187 | target instanceof HTMLTextAreaElement |
| 188 | ? target.name |
| 189 | : ""; |
| 190 | clearAuthFormFieldServerError(form, fieldName |
| 191 | onInput?.(event); |
| 192 | }} |
| 193 | onSubmit={submit} |
| 194 | > |
| 195 | {children} |
| 196 | </form> |
| 197 | ); |
| 198 | } |
| 199 | |
| 200 | type AuthFormTextFieldProps |
| 201 | ComponentProps<typeof |
| 202 | "name" | |
| 203 | > & { |
| 204 | description?: ReactNode |
| 205 | label: ReactNode |
| 206 | }; |
| 207 | |
| 208 | function AuthFormTextField({ |
| 209 | description, |
| 210 | id, |
| 211 | label, |
| 212 | ...props |
| 213 | }: AuthFormTextFieldProps) |
| 214 | const field = |
| 215 | const form = |
| 216 | const isInvalid = |
| 217 | const inputId = |
| 218 | |
| 219 | return ( |
| 220 | <Field data-invalid={ |
| 221 | <FieldLabel htmlFor={ |
| 222 | <Input |
| 223 | {...props} |
| 224 | aria-busy={field.state |
| 225 | aria-invalid={isInvalid} |
| 226 | id={inputId} |
| 227 | name={field.name |
| 228 | onBlur={field.handleBlur |
| 229 | onChange={(event) |
| 230 | clearAuthFormFieldServerError(form, field |
| 231 | field.handleChange(event |
| 232 | }} |
| 233 | value={field.state |
| 234 | /> |
| 235 | {description ? <FieldDescription |
| 236 | <AuthFormFieldError /> |
| 237 | </Field> |
| 238 | ); |
| 239 | } |
| 240 | |
| 241 | function AuthFormSubmitButton({ |
| 242 | children, |
| 243 | disabled, |
| 244 | isPending, |
| 245 | ...props |
| 246 | }: ComponentProps< |
| 247 | const form = |
| 248 | |
| 249 | return ( |
| 250 | <form.Subscribe |
| 251 | selector={(state) |
| 252 | > |
| 253 | {([isSubmitting, isValidating |
| 254 | <Button |
| 255 | {...props} |
| 256 | aria-busy={isPending || |
| 257 | aria-disabled={ |
| 258 | disabled || isPending |
| 259 | } |
| 260 | disabled={disabled || |
| 261 | type="submit" |
| 262 | > |
| 263 | {isPending || isSubmitting |
| 264 | <Spinner data-icon=" |
| 265 | ) : null} |
| 266 | {children} |
| 267 | </Button> |
| 268 | )} |
| 269 | </form.Subscribe> |
| 270 | ); |
| 271 | } |
| 272 | |
| 273 | type AuthFormAdditionalFieldProps |
| 274 | AdditionalFieldProps, |
| 275 | "errors" | |
| 276 | >; |
| 277 | |
| 278 | function AuthFormAdditionalField(props: |
| 279 | const field = |
| 280 | const form = |
| 281 | const isInvalid = |
| 282 | |
| 283 | return ( |
| 284 | <AdditionalField |
| 285 | {...props} |
| 286 | errors={ |
| 287 | isInvalid ? getFormFieldErrors( |
| 288 | } |
| 289 | isInvalid={isInvalid} |
| 290 | name={field.name |
| 291 | onBlur={field.handleBlur |
| 292 | onChange={(value) |
| 293 | clearAuthFormFieldServerError(form, field |
| 294 | field.handleChange(value |
| 295 | }} |
| 296 | value={field.state |
| 297 | /> |
| 298 | ); |
| 299 | } |
| 300 | |
| 301 | export const { |
| 302 | useAppForm: useAuthForm, |
| 303 | withFieldGroup: withAuthFieldGroup, |
| 304 | withForm: withAuthForm, |
| 305 | } = createFormHook({ |
| 306 | fieldComponents: { |
| 307 | AuthFormAdditionalField, |
| 308 | AuthFormFieldError, |
| 309 | AuthFormTextField, |
| 310 | }, |
| 311 | fieldContext, |
| 312 | formComponents: { |
| 313 | AuthFormRoot, |
| 314 | AuthFormServerError, |
| 315 | AuthFormSubmitButton, |
| 316 | }, |
| 317 | formContext, |
| 318 | }); |
| 319 | |
| 320 | export function isAuthFormFieldInvalid({ |
| 321 | isTouched, |
| 322 | isValid, |
| 323 | }: { |
| 324 | isTouched: boolean |
| 325 | isValid: boolean |
| 326 | }) { |
| 327 | return isTouched && |
| 328 | } |
| 329 | |
| 330 | export function getAuthAdditionalFieldValidators( |
| 331 | field: AdditionalFieldConfig |
| 332 | requiredMessage: string, |
| 333 | ) { |
| 334 | return { |
| 335 | onChange: ({ value |
| 336 | validateAdditionalFieldRequired(field, value |
| 337 | onChangeAsync: field.validate |
| 338 | ? ({ value |
| 339 | validateAdditionalFieldValue(field, value |
| 340 | : undefined, |
| 341 | onChangeAsyncDebounceMs: field.validate |
| 342 | ? (field.validateDebounceMs |
| 343 | DEFAULT_ADDITIONAL_FIELD_VALIDATION_DEBOUNCE_MS) |
| 344 | : undefined, |
| 345 | }; |
| 346 | } |