All files / src/components/form TextField.tsx

100% Statements 15/15
100% Branches 14/14
100% Functions 8/8
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                                        12691x 12691x 7736x   43228x   43228x 12691x 7736x         7736x   7736x             1614x     170x                
// A MUI text field bound to a TanStack Form field. Errors are reason codes
// (src/lib/reasons.ts), shown as text in the user's language under the field.
import MuiTextField, { type TextFieldProps } from '@mui/material/TextField'
import { useSelector, type AnyFieldApi } from '@tanstack/react-form'
import { reasonText, type Reason } from '#/lib/reasons'
import { firstReason } from './reason'
 
type Props = Omit<
  TextFieldProps,
  'name' | 'value' | 'onChange' | 'onBlur' | 'error' | 'helperText'
> & {
  field: AnyFieldApi
  /**
   * An error from outside the form's validators, e.g. a server function's
   * `code_wrong`. Shown instead of the validators' error.
   */
  reason?: Reason | undefined
}
 
export function TextField({ field, reason, disabled, ...props }: Props) {
  const errors = useSelector(field.store, (s): unknown[] => s.meta.errors)
  const blurred = useSelector(field.store, (s) => s.meta.isBlurred)
  const submitted = useSelector(
    field.form.store,
    (s) => s.submissionAttempts > 0,
  )
  const submitting = useSelector(field.form.store, (s) => s.isSubmitting)
  const value = useSelector(field.store, (s): unknown => s.value)
  const name = String(field.name)
 
  // Validator errors show once the user has left the field or submitted, not
  // while typing a first attempt.
  const shown =
    reason ?? (blurred || submitted ? firstReason(errors) : undefined)
 
  return (
    <MuiTextField
      {...props}
      id={props.id ?? name}
      name={name}
      value={typeof value === 'string' ? value : ''}
      onChange={(e) => {
        field.handleChange(e.target.value)
      }}
      onBlur={() => {
        field.handleBlur()
      }}
      disabled={disabled === true || submitting}
      error={shown !== undefined}
      helperText={shown === undefined ? undefined : reasonText(shown).text}
    />
  )
}